home *** CD-ROM | disk | FTP | other *** search
/ Libris Britannia 4 / science library(b).zip / science library(b) / DJGPP / BSN122DC.ZIP / docs / bison / bison.inf (.txt) next >
GNU Info File  |  1993-11-13  |  198KB  |  3,982 lines

  1. This is Info file bison.info, produced by Makeinfo-1.55 from the input
  2. file bison.tex.
  3.    This file documents the Bison parser generator.
  4.    Copyright (C) 1988, 1989, 1990, 1991, 1992 Free Software Foundation,
  5.    Permission is granted to make and distribute verbatim copies of this
  6. manual provided the copyright notice and this permission notice are
  7. preserved on all copies.
  8.    Permission is granted to copy and distribute modified versions of
  9. this manual under the conditions for verbatim copying, provided also
  10. that the sections entitled "GNU General Public License" and "Conditions
  11. for Using Bison" are included exactly as in the original, and provided
  12. that the entire resulting derived work is distributed under the terms
  13. of a permission notice identical to this one.
  14.    Permission is granted to copy and distribute translations of this
  15. manual into another language, under the above conditions for modified
  16. versions, except that the sections entitled "GNU General Public
  17. License", "Conditions for Using Bison" and this permission notice may be
  18. included in translations approved by the Free Software Foundation
  19. instead of in the original English.
  20. File: bison,  Node: Top,  Next: Introduction,  Prev: (dir),  Up: (dir)
  21.    This manual documents version 1.20 of Bison.
  22. * Menu:
  23. * Introduction::
  24. * Conditions::
  25. * Copying::           The GNU General Public License says
  26.                         how you can copy and share Bison
  27. Tutorial sections:
  28. * Concepts::          Basic concepts for understanding Bison.
  29. * Examples::          Three simple explained examples of using Bison.
  30. Reference sections:
  31. * Grammar File::      Writing Bison declarations and rules.
  32. * Interface::         C-language interface to the parser function `yyparse'.
  33. * Algorithm::         How the Bison parser works at run-time.
  34. * Error Recovery::    Writing rules for error recovery.
  35. * Context Dependency::  What to do if your language syntax is too
  36.                         messy for Bison to handle straightforwardly.
  37. * Debugging::         Debugging Bison parsers that parse wrong.
  38. * Invocation::        How to run Bison (to produce the parser source file).
  39. * Table of Symbols::  All the keywords of the Bison language are explained.
  40. * Glossary::          Basic concepts are explained.
  41. * Index::             Cross-references to the text.
  42.  -- The Detailed Node Listing --
  43. The Concepts of Bison
  44. * Language and Grammar::  Languages and context-free grammars,
  45.                             as mathematical ideas.
  46. * Grammar in Bison::  How we represent grammars for Bison's sake.
  47. * Semantic Values::   Each token or syntactic grouping can have
  48.                         a semantic value (the value of an integer,
  49.                         the name of an identifier, etc.).
  50. * Semantic Actions::  Each rule can have an action containing C code.
  51. * Bison Parser::      What are Bison's input and output,
  52.                         how is the output used?
  53. * Stages::            Stages in writing and running Bison grammars.
  54. * Grammar Layout::    Overall structure of a Bison grammar file.
  55. Examples
  56. * RPN Calc::          Reverse polish notation calculator;
  57.                         a first example with no operator precedence.
  58. * Infix Calc::        Infix (algebraic) notation calculator.
  59.                         Operator precedence is introduced.
  60. * Simple Error Recovery::  Continuing after syntax errors.
  61. * Multi-function Calc::    Calculator with memory and trig functions.
  62.                         It uses multiple data-types for semantic values.
  63. * Exercises::         Ideas for improving the multi-function calculator.
  64. Reverse Polish Notation Calculator
  65. * Decls: Rpcalc Decls.  Bison and C declarations for rpcalc.
  66. * Rules: Rpcalc Rules.  Grammar Rules for rpcalc, with explanation.
  67. * Lexer: Rpcalc Lexer.  The lexical analyzer.
  68. * Main: Rpcalc Main.    The controlling function.
  69. * Error: Rpcalc Error.  The error reporting function.
  70. * Gen: Rpcalc Gen.      Running Bison on the grammar file.
  71. * Comp: Rpcalc Compile. Run the C compiler on the output code.
  72. Grammar Rules for `rpcalc'
  73. * Rpcalc Input::
  74. * Rpcalc Line::
  75. * Rpcalc Expr::
  76. Multi-Function Calculator: `mfcalc'
  77. * Decl: Mfcalc Decl.      Bison declarations for multi-function calculator.
  78. * Rules: Mfcalc Rules.    Grammar rules for the calculator.
  79. * Symtab: Mfcalc Symtab.  Symbol table management subroutines.
  80. Bison Grammar Files
  81. * Grammar Outline::   Overall layout of the grammar file.
  82. * Symbols::           Terminal and nonterminal symbols.
  83. * Rules::             How to write grammar rules.
  84. * Recursion::         Writing recursive rules.
  85. * Semantics::         Semantic values and actions.
  86. * Declarations::      All kinds of Bison declarations are described here.
  87. * Multiple Parsers::  Putting more than one Bison parser in one program.
  88. Outline of a Bison Grammar
  89. * C Declarations::    Syntax and usage of the C declarations section.
  90. * Bison Declarations::  Syntax and usage of the Bison declarations section.
  91. * Grammar Rules::     Syntax and usage of the grammar rules section.
  92. * C Code::            Syntax and usage of the additional C code section.
  93. Defining Language Semantics
  94. * Value Type::        Specifying one data type for all semantic values.
  95. * Multiple Types::    Specifying several alternative data types.
  96. * Actions::           An action is the semantic definition of a grammar rule.
  97. * Action Types::      Specifying data types for actions to operate on.
  98. * Mid-Rule Actions::  Most actions go at the end of a rule.
  99.                       This says when, why and how to use the exceptional
  100.                         action in the middle of a rule.
  101. Bison Declarations
  102. * Token Decl::        Declaring terminal symbols.
  103. * Precedence Decl::   Declaring terminals with precedence and associativity.
  104. * Union Decl::        Declaring the set of all semantic value types.
  105. * Type Decl::         Declaring the choice of type for a nonterminal symbol.
  106. * Expect Decl::       Suppressing warnings about shift/reduce conflicts.
  107. * Start Decl::        Specifying the start symbol.
  108. * Pure Decl::         Requesting a reentrant parser.
  109. * Decl Summary::      Table of all Bison declarations.
  110. Parser C-Language Interface
  111. * Parser Function::   How to call `yyparse' and what it returns.
  112. * Lexical::           You must supply a function `yylex'
  113.                         which reads tokens.
  114. * Error Reporting::   You must supply a function `yyerror'.
  115. * Action Features::   Special features for use in actions.
  116. The Lexical Analyzer Function `yylex'
  117. * Calling Convention::  How `yyparse' calls `yylex'.
  118. * Token Values::      How `yylex' must return the semantic value
  119.                         of the token it has read.
  120. * Token Positions::   How `yylex' must return the text position
  121.                         (line number, etc.) of the token, if the
  122.                          actions want that.
  123. * Pure Calling::      How the calling convention differs
  124.                         in a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.).
  125. The Bison Parser Algorithm
  126. * Look-Ahead::        Parser looks one token ahead when deciding what to do.
  127. * Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
  128. * Precedence::        Operator precedence works by resolving conflicts.
  129. * Contextual Precedence::  When an operator's precedence depends on context.
  130. * Parser States::     The parser is a finite-state-machine with stack.
  131. * Reduce/Reduce::     When two rules are applicable in the same situation.
  132. * Mystery Conflicts::  Reduce/reduce conflicts that look unjustified.
  133. * Stack Overflow::    What happens when stack gets full.  How to avoid it.
  134. Operator Precedence
  135. * Why Precedence::    An example showing why precedence is needed.
  136. * Using Precedence::  How to specify precedence in Bison grammars.
  137. * Precedence Examples::  How these features are used in the previous example.
  138. * How Precedence::    How they work.
  139. Handling Context Dependencies
  140. * Semantic Tokens::   Token parsing can depend on the semantic context.
  141. * Lexical Tie-ins::   Token parsing can depend on the syntactic context.
  142. * Tie-in Recovery::   Lexical tie-ins have implications for how
  143.                         error recovery rules must be written.
  144. Invoking Bison
  145. * Bison Options::     All the options described in detail,
  146.             in alphabetical order by short options.
  147. * Option Cross Key::  Alphabetical list of long options.
  148. * VMS Invocation::    Bison command syntax on VMS.
  149. File: bison,  Node: Introduction,  Next: Conditions,  Prev: Top,  Up: Top
  150. Introduction
  151. ************
  152.    "Bison" is a general-purpose parser generator that converts a
  153. grammar description for an LALR(1) context-free grammar into a C
  154. program to parse that grammar.  Once you are proficient with Bison, you
  155. may use it to develop a wide range of language parsers, from those used
  156. in simple desk calculators to complex programming languages.
  157.    Bison is upward compatible with Yacc: all properly-written Yacc
  158. grammars ought to work with Bison with no change.  Anyone familiar with
  159. Yacc should be able to use Bison with little trouble.  You need to be
  160. fluent in C programming in order to use Bison or to understand this
  161. manual.
  162.    We begin with tutorial chapters that explain the basic concepts of
  163. using Bison and show three explained examples, each building on the
  164. last.  If you don't know Bison or Yacc, start by reading these
  165. chapters.  Reference chapters follow which describe specific aspects of
  166. Bison in detail.
  167.    Bison was written primarily by Robert Corbett; Richard Stallman made
  168. it Yacc-compatible.  This edition corresponds to version 1.20 of Bison.
  169. File: bison,  Node: Conditions,  Next: Copying,  Prev: Introduction,  Up: Top
  170. Conditions for Using Bison
  171. **************************
  172.    Bison grammars can be used only in programs that are free software.
  173. This is in contrast to what happens with the GNU C compiler and the
  174. other GNU programming tools.
  175.    The reason Bison is special is that the output of the Bison
  176. utility--the Bison parser file--contains a verbatim copy of a sizable
  177. piece of Bison, which is the code for the `yyparse' function.  (The
  178. actions from your grammar are inserted into this function at one point,
  179. but the rest of the function is not changed.)
  180.    As a result, the Bison parser file is covered by the same copying
  181. conditions that cover Bison itself and the rest of the GNU system: any
  182. program containing it has to be distributed under the standard GNU
  183. copying conditions.
  184.    Occasionally people who would like to use Bison to develop
  185. proprietary programs complain about this.
  186.    We don't particularly sympathize with their complaints.  The purpose
  187. of the GNU project is to promote the right to share software and the
  188. practice of sharing software; it is a means of changing society.  The
  189. people who complain are planning to be uncooperative toward the rest of
  190. the world; why should they deserve our help in doing so?
  191.    However, it's possible that a change in these conditions might
  192. encourage computer companies to use and distribute the GNU system.  If
  193. so, then we might decide to change the terms on `yyparse' as a matter
  194. of the strategy of promoting the right to share.  Such a change would be
  195. irrevocable.  Since we stand by the copying permissions we have
  196. announced, we cannot withdraw them once given.
  197.    We mustn't make an irrevocable change hastily.  We have to wait
  198. until there is a complete GNU system and there has been time to learn
  199. how this issue affects its reception.
  200. File: bison,  Node: Copying,  Next: Concepts,  Prev: Conditions,  Up: Top
  201. GNU GENERAL PUBLIC LICENSE
  202. **************************
  203.                          Version 2, June 1991
  204.      Copyright (C) 1989, 1991 Free Software Foundation, Inc.
  205.      675 Mass Ave, Cambridge, MA 02139, USA
  206.      
  207.      Everyone is permitted to copy and distribute verbatim copies
  208.      of this license document, but changing it is not allowed.
  209. Preamble
  210. ========
  211.    The licenses for most software are designed to take away your
  212. freedom to share and change it.  By contrast, the GNU General Public
  213. License is intended to guarantee your freedom to share and change free
  214. software--to make sure the software is free for all its users.  This
  215. General Public License applies to most of the Free Software
  216. Foundation's software and to any other program whose authors commit to
  217. using it.  (Some other Free Software Foundation software is covered by
  218. the GNU Library General Public License instead.)  You can apply it to
  219. your programs, too.
  220.    When we speak of free software, we are referring to freedom, not
  221. price.  Our General Public Licenses are designed to make sure that you
  222. have the freedom to distribute copies of free software (and charge for
  223. this service if you wish), that you receive source code or can get it
  224. if you want it, that you can change the software or use pieces of it in
  225. new free programs; and that you know you can do these things.
  226.    To protect your rights, we need to make restrictions that forbid
  227. anyone to deny you these rights or to ask you to surrender the rights.
  228. These restrictions translate to certain responsibilities for you if you
  229. distribute copies of the software, or if you modify it.
  230.    For example, if you distribute copies of such a program, whether
  231. gratis or for a fee, you must give the recipients all the rights that
  232. you have.  You must make sure that they, too, receive or can get the
  233. source code.  And you must show them these terms so they know their
  234. rights.
  235.    We protect your rights with two steps: (1) copyright the software,
  236. and (2) offer you this license which gives you legal permission to copy,
  237. distribute and/or modify the software.
  238.    Also, for each author's protection and ours, we want to make certain
  239. that everyone understands that there is no warranty for this free
  240. software.  If the software is modified by someone else and passed on, we
  241. want its recipients to know that what they have is not the original, so
  242. that any problems introduced by others will not reflect on the original
  243. authors' reputations.
  244.    Finally, any free program is threatened constantly by software
  245. patents.  We wish to avoid the danger that redistributors of a free
  246. program will individually obtain patent licenses, in effect making the
  247. program proprietary.  To prevent this, we have made it clear that any
  248. patent must be licensed for everyone's free use or not licensed at all.
  249.    The precise terms and conditions for copying, distribution and
  250. modification follow.
  251.     TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  252.   0. This License applies to any program or other work which contains a
  253.      notice placed by the copyright holder saying it may be distributed
  254.      under the terms of this General Public License.  The "Program",
  255.      below, refers to any such program or work, and a "work based on
  256.      the Program" means either the Program or any derivative work under
  257.      copyright law: that is to say, a work containing the Program or a
  258.      portion of it, either verbatim or with modifications and/or
  259.      translated into another language.  (Hereinafter, translation is
  260.      included without limitation in the term "modification".)  Each
  261.      licensee is addressed as "you".
  262.      Activities other than copying, distribution and modification are
  263.      not covered by this License; they are outside its scope.  The act
  264.      of running the Program is not restricted, and the output from the
  265.      Program is covered only if its contents constitute a work based on
  266.      the Program (independent of having been made by running the
  267.      Program).  Whether that is true depends on what the Program does.
  268.   1. You may copy and distribute verbatim copies of the Program's
  269.      source code as you receive it, in any medium, provided that you
  270.      conspicuously and appropriately publish on each copy an appropriate
  271.      copyright notice and disclaimer of warranty; keep intact all the
  272.      notices that refer to this License and to the absence of any
  273.      warranty; and give any other recipients of the Program a copy of
  274.      this License along with the Program.
  275.      You may charge a fee for the physical act of transferring a copy,
  276.      and you may at your option offer warranty protection in exchange
  277.      for a fee.
  278.   2. You may modify your copy or copies of the Program or any portion
  279.      of it, thus forming a work based on the Program, and copy and
  280.      distribute such modifications or work under the terms of Section 1
  281.      above, provided that you also meet all of these conditions:
  282.        a. You must cause the modified files to carry prominent notices
  283.           stating that you changed the files and the date of any change.
  284.        b. You must cause any work that you distribute or publish, that
  285.           in whole or in part contains or is derived from the Program
  286.           or any part thereof, to be licensed as a whole at no charge
  287.           to all third parties under the terms of this License.
  288.        c. If the modified program normally reads commands interactively
  289.           when run, you must cause it, when started running for such
  290.           interactive use in the most ordinary way, to print or display
  291.           an announcement including an appropriate copyright notice and
  292.           a notice that there is no warranty (or else, saying that you
  293.           provide a warranty) and that users may redistribute the
  294.           program under these conditions, and telling the user how to
  295.           view a copy of this License.  (Exception: if the Program
  296.           itself is interactive but does not normally print such an
  297.           announcement, your work based on the Program is not required
  298.           to print an announcement.)
  299.      These requirements apply to the modified work as a whole.  If
  300.      identifiable sections of that work are not derived from the
  301.      Program, and can be reasonably considered independent and separate
  302.      works in themselves, then this License, and its terms, do not
  303.      apply to those sections when you distribute them as separate
  304.      works.  But when you distribute the same sections as part of a
  305.      whole which is a work based on the Program, the distribution of
  306.      the whole must be on the terms of this License, whose permissions
  307.      for other licensees extend to the entire whole, and thus to each
  308.      and every part regardless of who wrote it.
  309.      Thus, it is not the intent of this section to claim rights or
  310.      contest your rights to work written entirely by you; rather, the
  311.      intent is to exercise the right to control the distribution of
  312.      derivative or collective works based on the Program.
  313.      In addition, mere aggregation of another work not based on the
  314.      Program with the Program (or with a work based on the Program) on
  315.      a volume of a storage or distribution medium does not bring the
  316.      other work under the scope of this License.
  317.   3. You may copy and distribute the Program (or a work based on it,
  318.      under Section 2) in object code or executable form under the terms
  319.      of Sections 1 and 2 above provided that you also do one of the
  320.      following:
  321.        a. Accompany it with the complete corresponding machine-readable
  322.           source code, which must be distributed under the terms of
  323.           Sections 1 and 2 above on a medium customarily used for
  324.           software interchange; or,
  325.        b. Accompany it with a written offer, valid for at least three
  326.           years, to give any third party, for a charge no more than your
  327.           cost of physically performing source distribution, a complete
  328.           machine-readable copy of the corresponding source code, to be
  329.           distributed under the terms of Sections 1 and 2 above on a
  330.           medium customarily used for software interchange; or,
  331.        c. Accompany it with the information you received as to the offer
  332.           to distribute corresponding source code.  (This alternative is
  333.           allowed only for noncommercial distribution and only if you
  334.           received the program in object code or executable form with
  335.           such an offer, in accord with Subsection b above.)
  336.      The source code for a work means the preferred form of the work for
  337.      making modifications to it.  For an executable work, complete
  338.      source code means all the source code for all modules it contains,
  339.      plus any associated interface definition files, plus the scripts
  340.      used to control compilation and installation of the executable.
  341.      However, as a special exception, the source code distributed need
  342.      not include anything that is normally distributed (in either
  343.      source or binary form) with the major components (compiler,
  344.      kernel, and so on) of the operating system on which the executable
  345.      runs, unless that component itself accompanies the executable.
  346.      If distribution of executable or object code is made by offering
  347.      access to copy from a designated place, then offering equivalent
  348.      access to copy the source code from the same place counts as
  349.      distribution of the source code, even though third parties are not
  350.      compelled to copy the source along with the object code.
  351.   4. You may not copy, modify, sublicense, or distribute the Program
  352.      except as expressly provided under this License.  Any attempt
  353.      otherwise to copy, modify, sublicense or distribute the Program is
  354.      void, and will automatically terminate your rights under this
  355.      License.  However, parties who have received copies, or rights,
  356.      from you under this License will not have their licenses
  357.      terminated so long as such parties remain in full compliance.
  358.   5. You are not required to accept this License, since you have not
  359.      signed it.  However, nothing else grants you permission to modify
  360.      or distribute the Program or its derivative works.  These actions
  361.      are prohibited by law if you do not accept this License.
  362.      Therefore, by modifying or distributing the Program (or any work
  363.      based on the Program), you indicate your acceptance of this
  364.      License to do so, and all its terms and conditions for copying,
  365.      distributing or modifying the Program or works based on it.
  366.   6. Each time you redistribute the Program (or any work based on the
  367.      Program), the recipient automatically receives a license from the
  368.      original licensor to copy, distribute or modify the Program
  369.      subject to these terms and conditions.  You may not impose any
  370.      further restrictions on the recipients' exercise of the rights
  371.      granted herein.  You are not responsible for enforcing compliance
  372.      by third parties to this License.
  373.   7. If, as a consequence of a court judgment or allegation of patent
  374.      infringement or for any other reason (not limited to patent
  375.      issues), conditions are imposed on you (whether by court order,
  376.      agreement or otherwise) that contradict the conditions of this
  377.      License, they do not excuse you from the conditions of this
  378.      License.  If you cannot distribute so as to satisfy simultaneously
  379.      your obligations under this License and any other pertinent
  380.      obligations, then as a consequence you may not distribute the
  381.      Program at all.  For example, if a patent license would not permit
  382.      royalty-free redistribution of the Program by all those who
  383.      receive copies directly or indirectly through you, then the only
  384.      way you could satisfy both it and this License would be to refrain
  385.      entirely from distribution of the Program.
  386.      If any portion of this section is held invalid or unenforceable
  387.      under any particular circumstance, the balance of the section is
  388.      intended to apply and the section as a whole is intended to apply
  389.      in other circumstances.
  390.      It is not the purpose of this section to induce you to infringe any
  391.      patents or other property right claims or to contest validity of
  392.      any such claims; this section has the sole purpose of protecting
  393.      the integrity of the free software distribution system, which is
  394.      implemented by public license practices.  Many people have made
  395.      generous contributions to the wide range of software distributed
  396.      through that system in reliance on consistent application of that
  397.      system; it is up to the author/donor to decide if he or she is
  398.      willing to distribute software through any other system and a
  399.      licensee cannot impose that choice.
  400.      This section is intended to make thoroughly clear what is believed
  401.      to be a consequence of the rest of this License.
  402.   8. If the distribution and/or use of the Program is restricted in
  403.      certain countries either by patents or by copyrighted interfaces,
  404.      the original copyright holder who places the Program under this
  405.      License may add an explicit geographical distribution limitation
  406.      excluding those countries, so that distribution is permitted only
  407.      in or among countries not thus excluded.  In such case, this
  408.      License incorporates the limitation as if written in the body of
  409.      this License.
  410.   9. The Free Software Foundation may publish revised and/or new
  411.      versions of the General Public License from time to time.  Such
  412.      new versions will be similar in spirit to the present version, but
  413.      may differ in detail to address new problems or concerns.
  414.      Each version is given a distinguishing version number.  If the
  415.      Program specifies a version number of this License which applies
  416.      to it and "any later version", you have the option of following
  417.      the terms and conditions either of that version or of any later
  418.      version published by the Free Software Foundation.  If the Program
  419.      does not specify a version number of this License, you may choose
  420.      any version ever published by the Free Software Foundation.
  421.  10. If you wish to incorporate parts of the Program into other free
  422.      programs whose distribution conditions are different, write to the
  423.      author to ask for permission.  For software which is copyrighted
  424.      by the Free Software Foundation, write to the Free Software
  425.      Foundation; we sometimes make exceptions for this.  Our decision
  426.      will be guided by the two goals of preserving the free status of
  427.      all derivatives of our free software and of promoting the sharing
  428.      and reuse of software generally.
  429.                                 NO WARRANTY
  430.  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
  431.      WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
  432.      LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
  433.      HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
  434.      WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
  435.      NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  436.      FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE
  437.      QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  438.      PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
  439.      SERVICING, REPAIR OR CORRECTION.
  440.  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
  441.      WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
  442.      MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
  443.      LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
  444.      INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
  445.      INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
  446.      DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
  447.      OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
  448.      OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
  449.      ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  450.                       END OF TERMS AND CONDITIONS
  451. How to Apply These Terms to Your New Programs
  452. =============================================
  453.    If you develop a new program, and you want it to be of the greatest
  454. possible use to the public, the best way to achieve this is to make it
  455. free software which everyone can redistribute and change under these
  456. terms.
  457.    To do so, attach the following notices to the program.  It is safest
  458. to attach them to the start of each source file to most effectively
  459. convey the exclusion of warranty; and each file should have at least
  460. the "copyright" line and a pointer to where the full notice is found.
  461.      ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
  462.      Copyright (C) 19YY  NAME OF AUTHOR
  463.      
  464.      This program is free software; you can redistribute it and/or modify
  465.      it under the terms of the GNU General Public License as published by
  466.      the Free Software Foundation; either version 2 of the License, or
  467.      (at your option) any later version.
  468.      
  469.      This program is distributed in the hope that it will be useful,
  470.      but WITHOUT ANY WARRANTY; without even the implied warranty of
  471.      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  472.      GNU General Public License for more details.
  473.      
  474.      You should have received a copy of the GNU General Public License
  475.      along with this program; if not, write to the Free Software
  476.      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  477.    Also add information on how to contact you by electronic and paper
  478. mail.
  479.    If the program is interactive, make it output a short notice like
  480. this when it starts in an interactive mode:
  481.      Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
  482.      Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  483.      type `show w'.
  484.      This is free software, and you are welcome to redistribute it
  485.      under certain conditions; type `show c' for details.
  486.    The hypothetical commands `show w' and `show c' should show the
  487. appropriate parts of the General Public License.  Of course, the
  488. commands you use may be called something other than `show w' and `show
  489. c'; they could even be mouse-clicks or menu items--whatever suits your
  490. program.
  491.    You should also get your employer (if you work as a programmer) or
  492. your school, if any, to sign a "copyright disclaimer" for the program,
  493. if necessary.  Here is a sample; alter the names:
  494.      Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  495.      `Gnomovision' (which makes passes at compilers) written by James Hacker.
  496.      
  497.      SIGNATURE OF TY COON, 1 April 1989
  498.      Ty Coon, President of Vice
  499.    This General Public License does not permit incorporating your
  500. program into proprietary programs.  If your program is a subroutine
  501. library, you may consider it more useful to permit linking proprietary
  502. applications with the library.  If this is what you want to do, use the
  503. GNU Library General Public License instead of this License.
  504. File: bison,  Node: Concepts,  Next: Examples,  Prev: Copying,  Up: Top
  505. The Concepts of Bison
  506. *********************
  507.    This chapter introduces many of the basic concepts without which the
  508. details of Bison will not make sense.  If you do not already know how to
  509. use Bison or Yacc, we suggest you start by reading this chapter
  510. carefully.
  511. * Menu:
  512. * Language and Grammar::  Languages and context-free grammars,
  513.                             as mathematical ideas.
  514. * Grammar in Bison::  How we represent grammars for Bison's sake.
  515. * Semantic Values::   Each token or syntactic grouping can have
  516.                         a semantic value (the value of an integer,
  517.                         the name of an identifier, etc.).
  518. * Semantic Actions::  Each rule can have an action containing C code.
  519. * Bison Parser::      What are Bison's input and output,
  520.                         how is the output used?
  521. * Stages::            Stages in writing and running Bison grammars.
  522. * Grammar Layout::    Overall structure of a Bison grammar file.
  523. File: bison,  Node: Language and Grammar,  Next: Grammar in Bison,  Up: Concepts
  524. Languages and Context-Free Grammars
  525. ===================================
  526.    In order for Bison to parse a language, it must be described by a
  527. "context-free grammar".  This means that you specify one or more
  528. "syntactic groupings" and give rules for constructing them from their
  529. parts.  For example, in the C language, one kind of grouping is called
  530. an `expression'.  One rule for making an expression might be, "An
  531. expression can be made of a minus sign and another expression".
  532. Another would be, "An expression can be an integer".  As you can see,
  533. rules are often recursive, but there must be at least one rule which
  534. leads out of the recursion.
  535.    The most common formal system for presenting such rules for humans
  536. to read is "Backus-Naur Form" or "BNF", which was developed in order to
  537. specify the language Algol 60.  Any grammar expressed in BNF is a
  538. context-free grammar.  The input to Bison is essentially
  539. machine-readable BNF.
  540.    Not all context-free languages can be handled by Bison, only those
  541. that are LALR(1).  In brief, this means that it must be possible to
  542. tell how to parse any portion of an input string with just a single
  543. token of look-ahead.  Strictly speaking, that is a description of an
  544. LR(1) grammar, and LALR(1) involves additional restrictions that are
  545. hard to explain simply; but it is rare in actual practice to find an
  546. LR(1) grammar that fails to be LALR(1).  *Note Mysterious Reduce/Reduce
  547. Conflicts: Mystery Conflicts, for more information on this.
  548.    In the formal grammatical rules for a language, each kind of
  549. syntactic unit or grouping is named by a "symbol".  Those which are
  550. built by grouping smaller constructs according to grammatical rules are
  551. called "nonterminal symbols"; those which can't be subdivided are called
  552. "terminal symbols" or "token types".  We call a piece of input
  553. corresponding to a single terminal symbol a "token", and a piece
  554. corresponding to a single nonterminal symbol a "grouping".
  555.    We can use the C language as an example of what symbols, terminal and
  556. nonterminal, mean.  The tokens of C are identifiers, constants (numeric
  557. and string), and the various keywords, arithmetic operators and
  558. punctuation marks.  So the terminal symbols of a grammar for C include
  559. `identifier', `number', `string', plus one symbol for each keyword,
  560. operator or punctuation mark: `if', `return', `const', `static', `int',
  561. `char', `plus-sign', `open-brace', `close-brace', `comma' and many
  562. more.  (These tokens can be subdivided into characters, but that is a
  563. matter of lexicography, not grammar.)
  564.    Here is a simple C function subdivided into tokens:
  565.      int             /* keyword `int' */
  566.      square (x)      /* identifier, open-paren, */
  567.                      /* identifier, close-paren */
  568.           int x;     /* keyword `int', identifier, semicolon */
  569.      {               /* open-brace */
  570.        return x * x; /* keyword `return', identifier, */
  571.                      /* asterisk, identifier, semicolon */
  572.      }               /* close-brace */
  573.    The syntactic groupings of C include the expression, the statement,
  574. the declaration, and the function definition.  These are represented in
  575. the grammar of C by nonterminal symbols `expression', `statement',
  576. `declaration' and `function definition'.  The full grammar uses dozens
  577. of additional language constructs, each with its own nonterminal
  578. symbol, in order to express the meanings of these four.  The example
  579. above is a function definition; it contains one declaration, and one
  580. statement.  In the statement, each `x' is an expression and so is `x *
  581.    Each nonterminal symbol must have grammatical rules showing how it
  582. is made out of simpler constructs.  For example, one kind of C
  583. statement is the `return' statement; this would be described with a
  584. grammar rule which reads informally as follows:
  585.      A `statement' can be made of a `return' keyword, an `expression'
  586.      and a `semicolon'.
  587. There would be many other rules for `statement', one for each kind of
  588. statement in C.
  589.    One nonterminal symbol must be distinguished as the special one which
  590. defines a complete utterance in the language.  It is called the "start
  591. symbol".  In a compiler, this means a complete input program.  In the C
  592. language, the nonterminal symbol `sequence of definitions and
  593. declarations' plays this role.
  594.    For example, `1 + 2' is a valid C expression--a valid part of a C
  595. program--but it is not valid as an *entire* C program.  In the
  596. context-free grammar of C, this follows from the fact that `expression'
  597. is not the start symbol.
  598.    The Bison parser reads a sequence of tokens as its input, and groups
  599. the tokens using the grammar rules.  If the input is valid, the end
  600. result is that the entire token sequence reduces to a single grouping
  601. whose symbol is the grammar's start symbol.  If we use a grammar for C,
  602. the entire input must be a `sequence of definitions and declarations'.
  603. If not, the parser reports a syntax error.
  604. File: bison,  Node: Grammar in Bison,  Next: Semantic Values,  Prev: Language and Grammar,  Up: Concepts
  605. From Formal Rules to Bison Input
  606. ================================
  607.    A formal grammar is a mathematical construct.  To define the language
  608. for Bison, you must write a file expressing the grammar in Bison syntax:
  609. a "Bison grammar" file.  *Note Bison Grammar Files: Grammar File.
  610.    A nonterminal symbol in the formal grammar is represented in Bison
  611. input as an identifier, like an identifier in C.  By convention, it
  612. should be in lower case, such as `expr', `stmt' or `declaration'.
  613.    The Bison representation for a terminal symbol is also called a
  614. "token type".  Token types as well can be represented as C-like
  615. identifiers.  By convention, these identifiers should be upper case to
  616. distinguish them from nonterminals: for example, `INTEGER',
  617. `IDENTIFIER', `IF' or `RETURN'.  A terminal symbol that stands for a
  618. particular keyword in the language should be named after that keyword
  619. converted to upper case.  The terminal symbol `error' is reserved for
  620. error recovery.  *Note Symbols::.
  621.    A terminal symbol can also be represented as a character literal,
  622. just like a C character constant.  You should do this whenever a token
  623. is just a single character (parenthesis, plus-sign, etc.): use that
  624. same character in a literal as the terminal symbol for that token.
  625.    The grammar rules also have an expression in Bison syntax.  For
  626. example, here is the Bison rule for a C `return' statement.  The
  627. semicolon in quotes is a literal character token, representing part of
  628. the C syntax for the statement; the naked semicolon, and the colon, are
  629. Bison punctuation used in every rule.
  630.      stmt:   RETURN expr ';'
  631.              ;
  632. *Note Syntax of Grammar Rules: Rules.
  633. File: bison,  Node: Semantic Values,  Next: Semantic Actions,  Prev: Grammar in Bison,  Up: Concepts
  634. Semantic Values
  635. ===============
  636.    A formal grammar selects tokens only by their classifications: for
  637. example, if a rule mentions the terminal symbol `integer constant', it
  638. means that *any* integer constant is grammatically valid in that
  639. position.  The precise value of the constant is irrelevant to how to
  640. parse the input: if `x+4' is grammatical then `x+1' or `x+3989' is
  641. equally grammatical.
  642.    But the precise value is very important for what the input means
  643. once it is parsed.  A compiler is useless if it fails to distinguish
  644. between 4, 1 and 3989 as constants in the program!  Therefore, each
  645. token in a Bison grammar has both a token type and a "semantic value".
  646. *Note Defining Language Semantics: Semantics, for details.
  647.    The token type is a terminal symbol defined in the grammar, such as
  648. `INTEGER', `IDENTIFIER' or `',''.  It tells everything you need to know
  649. to decide where the token may validly appear and how to group it with
  650. other tokens.  The grammar rules know nothing about tokens except their
  651. types.
  652.    The semantic value has all the rest of the information about the
  653. meaning of the token, such as the value of an integer, or the name of an
  654. identifier.  (A token such as `','' which is just punctuation doesn't
  655. need to have any semantic value.)
  656.    For example, an input token might be classified as token type
  657. `INTEGER' and have the semantic value 4.  Another input token might
  658. have the same token type `INTEGER' but value 3989.  When a grammar rule
  659. says that `INTEGER' is allowed, either of these tokens is acceptable
  660. because each is an `INTEGER'.  When the parser accepts the token, it
  661. keeps track of the token's semantic value.
  662.    Each grouping can also have a semantic value as well as its
  663. nonterminal symbol.  For example, in a calculator, an expression
  664. typically has a semantic value that is a number.  In a compiler for a
  665. programming language, an expression typically has a semantic value that
  666. is a tree structure describing the meaning of the expression.
  667. File: bison,  Node: Semantic Actions,  Next: Bison Parser,  Prev: Semantic Values,  Up: Concepts
  668. Semantic Actions
  669. ================
  670.    In order to be useful, a program must do more than parse input; it
  671. must also produce some output based on the input.  In a Bison grammar,
  672. a grammar rule can have an "action" made up of C statements.  Each time
  673. the parser recognizes a match for that rule, the action is executed.
  674. *Note Actions::.
  675.    Most of the time, the purpose of an action is to compute the
  676. semantic value of the whole construct from the semantic values of its
  677. parts.  For example, suppose we have a rule which says an expression
  678. can be the sum of two expressions.  When the parser recognizes such a
  679. sum, each of the subexpressions has a semantic value which describes
  680. how it was built up.  The action for this rule should create a similar
  681. sort of value for the newly recognized larger expression.
  682.    For example, here is a rule that says an expression can be the sum of
  683. two subexpressions:
  684.      expr: expr '+' expr   { $$ = $1 + $3; }
  685.              ;
  686. The action says how to produce the semantic value of the sum expression
  687. from the values of the two subexpressions.
  688. File: bison,  Node: Bison Parser,  Next: Stages,  Prev: Semantic Actions,  Up: Concepts
  689. Bison Output: the Parser File
  690. =============================
  691.    When you run Bison, you give it a Bison grammar file as input.  The
  692. output is a C source file that parses the language described by the
  693. grammar.  This file is called a "Bison parser".  Keep in mind that the
  694. Bison utility and the Bison parser are two distinct programs: the Bison
  695. utility is a program whose output is the Bison parser that becomes part
  696. of your program.
  697.    The job of the Bison parser is to group tokens into groupings
  698. according to the grammar rules--for example, to build identifiers and
  699. operators into expressions.  As it does this, it runs the actions for
  700. the grammar rules it uses.
  701.    The tokens come from a function called the "lexical analyzer" that
  702. you must supply in some fashion (such as by writing it in C).  The
  703. Bison parser calls the lexical analyzer each time it wants a new token.
  704. It doesn't know what is "inside" the tokens (though their semantic
  705. values may reflect this).  Typically the lexical analyzer makes the
  706. tokens by parsing characters of text, but Bison does not depend on
  707. this.  *Note The Lexical Analyzer Function `yylex': Lexical.
  708.    The Bison parser file is C code which defines a function named
  709. `yyparse' which implements that grammar.  This function does not make a
  710. complete C program: you must supply some additional functions.  One is
  711. the lexical analyzer.  Another is an error-reporting function which the
  712. parser calls to report an error.  In addition, a complete C program must
  713. start with a function called `main'; you have to provide this, and
  714. arrange for it to call `yyparse' or the parser will never run.  *Note
  715. Parser C-Language Interface: Interface.
  716.    Aside from the token type names and the symbols in the actions you
  717. write, all variable and function names used in the Bison parser file
  718. begin with `yy' or `YY'.  This includes interface functions such as the
  719. lexical analyzer function `yylex', the error reporting function
  720. `yyerror' and the parser function `yyparse' itself.  This also includes
  721. numerous identifiers used for internal purposes.  Therefore, you should
  722. avoid using C identifiers starting with `yy' or `YY' in the Bison
  723. grammar file except for the ones defined in this manual.
  724. File: bison,  Node: Stages,  Next: Grammar Layout,  Prev: Bison Parser,  Up: Concepts
  725. Stages in Using Bison
  726. =====================
  727.    The actual language-design process using Bison, from grammar
  728. specification to a working compiler or interpreter, has these parts:
  729.   1. Formally specify the grammar in a form recognized by Bison (*note
  730.      Bison Grammar Files: Grammar File.).  For each grammatical rule in
  731.      the language, describe the action that is to be taken when an
  732.      instance of that rule is recognized.  The action is described by a
  733.      sequence of C statements.
  734.   2. Write a lexical analyzer to process input and pass tokens to the
  735.      parser.  The lexical analyzer may be written by hand in C (*note
  736.      The Lexical Analyzer Function `yylex': Lexical.).  It could also
  737.      be produced using Lex, but the use of Lex is not discussed in this
  738.      manual.
  739.   3. Write a controlling function that calls the Bison-produced parser.
  740.   4. Write error-reporting routines.
  741.    To turn this source code as written into a runnable program, you
  742. must follow these steps:
  743.   1. Run Bison on the grammar to produce the parser.
  744.   2. Compile the code output by Bison, as well as any other source
  745.      files.
  746.   3. Link the object files to produce the finished product.
  747. File: bison,  Node: Grammar Layout,  Prev: Stages,  Up: Concepts
  748. The Overall Layout of a Bison Grammar
  749. =====================================
  750.    The input file for the Bison utility is a "Bison grammar file".  The
  751. general form of a Bison grammar file is as follows:
  752.      %{
  753.      C DECLARATIONS
  754.      %}
  755.      
  756.      BISON DECLARATIONS
  757.      
  758.      %%
  759.      GRAMMAR RULES
  760.      %%
  761.      ADDITIONAL C CODE
  762. The `%%', `%{' and `%}' are punctuation that appears in every Bison
  763. grammar file to separate the sections.
  764.    The C declarations may define types and variables used in the
  765. actions.  You can also use preprocessor commands to define macros used
  766. there, and use `#include' to include header files that do any of these
  767. things.
  768.    The Bison declarations declare the names of the terminal and
  769. nonterminal symbols, and may also describe operator precedence and the
  770. data types of semantic values of various symbols.
  771.    The grammar rules define how to construct each nonterminal symbol
  772. from its parts.
  773.    The additional C code can contain any C code you want to use.  Often
  774. the definition of the lexical analyzer `yylex' goes here, plus
  775. subroutines called by the actions in the grammar rules.  In a simple
  776. program, all the rest of the program can go here.
  777. File: bison,  Node: Examples,  Next: Grammar File,  Prev: Concepts,  Up: Top
  778. Examples
  779. ********
  780.    Now we show and explain three sample programs written using Bison: a
  781. reverse polish notation calculator, an algebraic (infix) notation
  782. calculator, and a multi-function calculator.  All three have been tested
  783. under BSD Unix 4.3; each produces a usable, though limited, interactive
  784. desk-top calculator.
  785.    These examples are simple, but Bison grammars for real programming
  786. languages are written the same way.  You can copy these examples out of
  787. the Info file and into a source file to try them.
  788. * Menu:
  789. * RPN Calc::          Reverse polish notation calculator;
  790.                         a first example with no operator precedence.
  791. * Infix Calc::        Infix (algebraic) notation calculator.
  792.                         Operator precedence is introduced.
  793. * Simple Error Recovery::  Continuing after syntax errors.
  794. * Multi-function Calc::  Calculator with memory and trig functions.
  795.                            It uses multiple data-types for semantic values.
  796. * Exercises::         Ideas for improving the multi-function calculator.
  797. File: bison,  Node: RPN Calc,  Next: Infix Calc,  Up: Examples
  798. Reverse Polish Notation Calculator
  799. ==================================
  800.    The first example is that of a simple double-precision "reverse
  801. polish notation" calculator (a calculator using postfix operators).
  802. This example provides a good starting point, since operator precedence
  803. is not an issue.  The second example will illustrate how operator
  804. precedence is handled.
  805.    The source code for this calculator is named `rpcalc.y'.  The `.y'
  806. extension is a convention used for Bison input files.
  807. * Menu:
  808. * Decls: Rpcalc Decls.  Bison and C declarations for rpcalc.
  809. * Rules: Rpcalc Rules.  Grammar Rules for rpcalc, with explanation.
  810. * Lexer: Rpcalc Lexer.  The lexical analyzer.
  811. * Main: Rpcalc Main.    The controlling function.
  812. * Error: Rpcalc Error.  The error reporting function.
  813. * Gen: Rpcalc Gen.      Running Bison on the grammar file.
  814. * Comp: Rpcalc Compile. Run the C compiler on the output code.
  815. File: bison,  Node: Rpcalc Decls,  Next: Rpcalc Rules,  Up: RPN Calc
  816. Declarations for `rpcalc'
  817. -------------------------
  818.    Here are the C and Bison declarations for the reverse polish notation
  819. calculator.  As in C, comments are placed between `/*...*/'.
  820.      /* Reverse polish notation calculator. */
  821.      
  822.      %{
  823.      #define YYSTYPE double
  824.      #include <math.h>
  825.      %}
  826.      
  827.      %token NUM
  828.      
  829.      %% /* Grammar rules and actions follow */
  830.    The C declarations section (*note The C Declarations Section: C
  831. Declarations.) contains two preprocessor directives.
  832.    The `#define' directive defines the macro `YYSTYPE', thus specifying
  833. the C data type for semantic values of both tokens and groupings (*note
  834. Data Types of Semantic Values: Value Type.).  The Bison parser will use
  835. whatever type `YYSTYPE' is defined as; if you don't define it, `int' is
  836. the default.  Because we specify `double', each token and each
  837. expression has an associated value, which is a floating point number.
  838.    The `#include' directive is used to declare the exponentiation
  839. function `pow'.
  840.    The second section, Bison declarations, provides information to
  841. Bison about the token types (*note The Bison Declarations Section:
  842. Bison Declarations.).  Each terminal symbol that is not a
  843. single-character literal must be declared here.  (Single-character
  844. literals normally don't need to be declared.)  In this example, all the
  845. arithmetic operators are designated by single-character literals, so the
  846. only terminal symbol that needs to be declared is `NUM', the token type
  847. for numeric constants.
  848. File: bison,  Node: Rpcalc Rules,  Next: Rpcalc Lexer,  Prev: Rpcalc Decls,  Up: RPN Calc
  849. Grammar Rules for `rpcalc'
  850. --------------------------
  851.    Here are the grammar rules for the reverse polish notation
  852. calculator.
  853.      input:    /* empty */
  854.              | input line
  855.      ;
  856.      
  857.      line:     '\n'
  858.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  859.      ;
  860.      
  861.      exp:      NUM             { $$ = $1;         }
  862.              | exp exp '+'     { $$ = $1 + $2;    }
  863.              | exp exp '-'     { $$ = $1 - $2;    }
  864.              | exp exp '*'     { $$ = $1 * $2;    }
  865.              | exp exp '/'     { $$ = $1 / $2;    }
  866.            /* Exponentiation */
  867.              | exp exp '^'     { $$ = pow ($1, $2); }
  868.            /* Unary minus    */
  869.              | exp 'n'         { $$ = -$1;        }
  870.      ;
  871.      %%
  872.    The groupings of the rpcalc "language" defined here are the
  873. expression (given the name `exp'), the line of input (`line'), and the
  874. complete input transcript (`input').  Each of these nonterminal symbols
  875. has several alternate rules, joined by the `|' punctuator which is read
  876. as "or".  The following sections explain what these rules mean.
  877.    The semantics of the language is determined by the actions taken
  878. when a grouping is recognized.  The actions are the C code that appears
  879. inside braces.  *Note Actions::.
  880.    You must specify these actions in C, but Bison provides the means for
  881. passing semantic values between the rules.  In each action, the
  882. pseudo-variable `$$' stands for the semantic value for the grouping
  883. that the rule is going to construct.  Assigning a value to `$$' is the
  884. main job of most actions.  The semantic values of the components of the
  885. rule are referred to as `$1', `$2', and so on.
  886. * Menu:
  887. * Rpcalc Input::
  888. * Rpcalc Line::
  889. * Rpcalc Expr::
  890. File: bison,  Node: Rpcalc Input,  Next: Rpcalc Line,  Up: Rpcalc Rules
  891. Explanation of `input'
  892. ......................
  893.    Consider the definition of `input':
  894.      input:    /* empty */
  895.              | input line
  896.      ;
  897.    This definition reads as follows: "A complete input is either an
  898. empty string, or a complete input followed by an input line".  Notice
  899. that "complete input" is defined in terms of itself.  This definition
  900. is said to be "left recursive" since `input' appears always as the
  901. leftmost symbol in the sequence.  *Note Recursive Rules: Recursion.
  902.    The first alternative is empty because there are no symbols between
  903. the colon and the first `|'; this means that `input' can match an empty
  904. string of input (no tokens).  We write the rules this way because it is
  905. legitimate to type `Ctrl-d' right after you start the calculator.  It's
  906. conventional to put an empty alternative first and write the comment
  907. `/* empty */' in it.
  908.    The second alternate rule (`input line') handles all nontrivial
  909. input.  It means, "After reading any number of lines, read one more
  910. line if possible."  The left recursion makes this rule into a loop.
  911. Since the first alternative matches empty input, the loop can be
  912. executed zero or more times.
  913.    The parser function `yyparse' continues to process input until a
  914. grammatical error is seen or the lexical analyzer says there are no more
  915. input tokens; we will arrange for the latter to happen at end of file.
  916. File: bison,  Node: Rpcalc Line,  Next: Rpcalc Expr,  Prev: Rpcalc Input,  Up: Rpcalc Rules
  917. Explanation of `line'
  918. .....................
  919.    Now consider the definition of `line':
  920.      line:     '\n'
  921.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  922.      ;
  923.    The first alternative is a token which is a newline character; this
  924. means that rpcalc accepts a blank line (and ignores it, since there is
  925. no action).  The second alternative is an expression followed by a
  926. newline.  This is the alternative that makes rpcalc useful.  The
  927. semantic value of the `exp' grouping is the value of `$1' because the
  928. `exp' in question is the first symbol in the alternative.  The action
  929. prints this value, which is the result of the computation the user
  930. asked for.
  931.    This action is unusual because it does not assign a value to `$$'.
  932. As a consequence, the semantic value associated with the `line' is
  933. uninitialized (its value will be unpredictable).  This would be a bug if
  934. that value were ever used, but we don't use it: once rpcalc has printed
  935. the value of the user's input line, that value is no longer needed.
  936. File: bison,  Node: Rpcalc Expr,  Prev: Rpcalc Line,  Up: Rpcalc Rules
  937. Explanation of `expr'
  938. .....................
  939.    The `exp' grouping has several rules, one for each kind of
  940. expression.  The first rule handles the simplest expressions: those
  941. that are just numbers.  The second handles an addition-expression,
  942. which looks like two expressions followed by a plus-sign.  The third
  943. handles subtraction, and so on.
  944.      exp:      NUM
  945.              | exp exp '+'     { $$ = $1 + $2;    }
  946.              | exp exp '-'     { $$ = $1 - $2;    }
  947.              ...
  948.              ;
  949.    We have used `|' to join all the rules for `exp', but we could
  950. equally well have written them separately:
  951.      exp:      NUM ;
  952.      exp:      exp exp '+'     { $$ = $1 + $2;    } ;
  953.      exp:      exp exp '-'     { $$ = $1 - $2;    } ;
  954.              ...
  955.    Most of the rules have actions that compute the value of the
  956. expression in terms of the value of its parts.  For example, in the
  957. rule for addition, `$1' refers to the first component `exp' and `$2'
  958. refers to the second one.  The third component, `'+'', has no meaningful
  959. associated semantic value, but if it had one you could refer to it as
  960. `$3'.  When `yyparse' recognizes a sum expression using this rule, the
  961. sum of the two subexpressions' values is produced as the value of the
  962. entire expression.  *Note Actions::.
  963.    You don't have to give an action for every rule.  When a rule has no
  964. action, Bison by default copies the value of `$1' into `$$'.  This is
  965. what happens in the first rule (the one that uses `NUM').
  966.    The formatting shown here is the recommended convention, but Bison
  967. does not require it.  You can add or change whitespace as much as you
  968. wish.  For example, this:
  969.      exp   : NUM | exp exp '+' {$$ = $1 + $2; } | ...
  970. means the same thing as this:
  971.      exp:      NUM
  972.              | exp exp '+'    { $$ = $1 + $2; }
  973.              | ...
  974. The latter, however, is much more readable.
  975. File: bison,  Node: Rpcalc Lexer,  Next: Rpcalc Main,  Prev: Rpcalc Rules,  Up: RPN Calc
  976. The `rpcalc' Lexical Analyzer
  977. -----------------------------
  978.    The lexical analyzer's job is low-level parsing: converting
  979. characters or sequences of characters into tokens.  The Bison parser
  980. gets its tokens by calling the lexical analyzer.  *Note The Lexical
  981. Analyzer Function `yylex': Lexical.
  982.    Only a simple lexical analyzer is needed for the RPN calculator.
  983. This lexical analyzer skips blanks and tabs, then reads in numbers as
  984. `double' and returns them as `NUM' tokens.  Any other character that
  985. isn't part of a number is a separate token.  Note that the token-code
  986. for such a single-character token is the character itself.
  987.    The return value of the lexical analyzer function is a numeric code
  988. which represents a token type.  The same text used in Bison rules to
  989. stand for this token type is also a C expression for the numeric code
  990. for the type.  This works in two ways.  If the token type is a
  991. character literal, then its numeric code is the ASCII code for that
  992. character; you can use the same character literal in the lexical
  993. analyzer to express the number.  If the token type is an identifier,
  994. that identifier is defined by Bison as a C macro whose definition is
  995. the appropriate number.  In this example, therefore, `NUM' becomes a
  996. macro for `yylex' to use.
  997.    The semantic value of the token (if it has one) is stored into the
  998. global variable `yylval', which is where the Bison parser will look for
  999. it.  (The C data type of `yylval' is `YYSTYPE', which was defined at
  1000. the beginning of the grammar; *note Declarations for `rpcalc': Rpcalc
  1001. Decls..)
  1002.    A token type code of zero is returned if the end-of-file is
  1003. encountered.  (Bison recognizes any nonpositive value as indicating the
  1004. end of the input.)
  1005.    Here is the code for the lexical analyzer:
  1006.      /* Lexical analyzer returns a double floating point
  1007.         number on the stack and the token NUM, or the ASCII
  1008.         character read if not a number.  Skips all blanks
  1009.         and tabs, returns 0 for EOF. */
  1010.      
  1011.      #include <ctype.h>
  1012.      
  1013.      yylex ()
  1014.      {
  1015.        int c;
  1016.      
  1017.        /* skip white space  */
  1018.        while ((c = getchar ()) == ' ' || c == '\t')
  1019.          ;
  1020.        /* process numbers   */
  1021.        if (c == '.' || isdigit (c))
  1022.          {
  1023.            ungetc (c, stdin);
  1024.            scanf ("%lf", &yylval);
  1025.            return NUM;
  1026.          }
  1027.        /* return end-of-file  */
  1028.        if (c == EOF)
  1029.          return 0;
  1030.        /* return single chars */
  1031.        return c;
  1032.      }
  1033. File: bison,  Node: Rpcalc Main,  Next: Rpcalc Error,  Prev: Rpcalc Lexer,  Up: RPN Calc
  1034. The Controlling Function
  1035. ------------------------
  1036.    In keeping with the spirit of this example, the controlling function
  1037. is kept to the bare minimum.  The only requirement is that it call
  1038. `yyparse' to start the process of parsing.
  1039.      main ()
  1040.      {
  1041.        yyparse ();
  1042.      }
  1043. File: bison,  Node: Rpcalc Error,  Next: Rpcalc Gen,  Prev: Rpcalc Main,  Up: RPN Calc
  1044. The Error Reporting Routine
  1045. ---------------------------
  1046.    When `yyparse' detects a syntax error, it calls the error reporting
  1047. function `yyerror' to print an error message (usually but not always
  1048. `"parse error"').  It is up to the programmer to supply `yyerror'
  1049. (*note Parser C-Language Interface: Interface.), so here is the
  1050. definition we will use:
  1051.      #include <stdio.h>
  1052.      
  1053.      yyerror (s)  /* Called by yyparse on error */
  1054.           char *s;
  1055.      {
  1056.        printf ("%s\n", s);
  1057.      }
  1058.    After `yyerror' returns, the Bison parser may recover from the error
  1059. and continue parsing if the grammar contains a suitable error rule
  1060. (*note Error Recovery::.).  Otherwise, `yyparse' returns nonzero.  We
  1061. have not written any error rules in this example, so any invalid input
  1062. will cause the calculator program to exit.  This is not clean behavior
  1063. for a real calculator, but it is adequate in the first example.
  1064. File: bison,  Node: Rpcalc Gen,  Next: Rpcalc Compile,  Prev: Rpcalc Error,  Up: RPN Calc
  1065. Running Bison to Make the Parser
  1066. --------------------------------
  1067.    Before running Bison to produce a parser, we need to decide how to
  1068. arrange all the source code in one or more source files.  For such a
  1069. simple example, the easiest thing is to put everything in one file.
  1070. The definitions of `yylex', `yyerror' and `main' go at the end, in the
  1071. "additional C code" section of the file (*note The Overall Layout of a
  1072. Bison Grammar: Grammar Layout.).
  1073.    For a large project, you would probably have several source files,
  1074. and use `make' to arrange to recompile them.
  1075.    With all the source in a single file, you use the following command
  1076. to convert it into a parser file:
  1077.      bison FILE_NAME.y
  1078. In this example the file was called `rpcalc.y' (for "Reverse Polish
  1079. CALCulator").  Bison produces a file named `FILE_NAME.tab.c', removing
  1080. the `.y' from the original file name. The file output by Bison contains
  1081. the source code for `yyparse'.  The additional functions in the input
  1082. file (`yylex', `yyerror' and `main') are copied verbatim to the output.
  1083. File: bison,  Node: Rpcalc Compile,  Prev: Rpcalc Gen,  Up: RPN Calc
  1084. Compiling the Parser File
  1085. -------------------------
  1086.    Here is how to compile and run the parser file:
  1087.      # List files in current directory.
  1088.      % ls
  1089.      rpcalc.tab.c  rpcalc.y
  1090.      
  1091.      # Compile the Bison parser.
  1092.      # `-lm' tells compiler to search math library for `pow'.
  1093.      % cc rpcalc.tab.c -lm -o rpcalc
  1094.      
  1095.      # List files again.
  1096.      % ls
  1097.      rpcalc  rpcalc.tab.c  rpcalc.y
  1098.    The file `rpcalc' now contains the executable code.  Here is an
  1099. example session using `rpcalc'.
  1100.      % rpcalc
  1101.      4 9 +
  1102.      13
  1103.      3 7 + 3 4 5 *+-
  1104.      -13
  1105.      3 7 + 3 4 5 * + - n              Note the unary minus, `n'
  1106.      13
  1107.      5 6 / 4 n +
  1108.      -3.166666667
  1109.      3 4 ^                            Exponentiation
  1110.      81
  1111.      ^D                               End-of-file indicator
  1112.      %
  1113. File: bison,  Node: Infix Calc,  Next: Simple Error Recovery,  Prev: RPN Calc,  Up: Examples
  1114. Infix Notation Calculator: `calc'
  1115. =================================
  1116.    We now modify rpcalc to handle infix operators instead of postfix.
  1117. Infix notation involves the concept of operator precedence and the need
  1118. for parentheses nested to arbitrary depth.  Here is the Bison code for
  1119. `calc.y', an infix desk-top calculator.
  1120.      /* Infix notation calculator--calc */
  1121.      
  1122.      %{
  1123.      #define YYSTYPE double
  1124.      #include <math.h>
  1125.      %}
  1126.      
  1127.      /* BISON Declarations */
  1128.      %token NUM
  1129.      %left '-' '+'
  1130.      %left '*' '/'
  1131.      %left NEG     /* negation--unary minus */
  1132.      %right '^'    /* exponentiation        */
  1133.      
  1134.      /* Grammar follows */
  1135.      %%
  1136.      input:    /* empty string */
  1137.              | input line
  1138.      ;
  1139.      
  1140.      line:     '\n'
  1141.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  1142.      ;
  1143.      
  1144.      exp:      NUM                { $$ = $1;         }
  1145.              | exp '+' exp        { $$ = $1 + $3;    }
  1146.              | exp '-' exp        { $$ = $1 - $3;    }
  1147.              | exp '*' exp        { $$ = $1 * $3;    }
  1148.              | exp '/' exp        { $$ = $1 / $3;    }
  1149.              | '-' exp  %prec NEG { $$ = -$2;        }
  1150.              | exp '^' exp        { $$ = pow ($1, $3); }
  1151.              | '(' exp ')'        { $$ = $2;         }
  1152.      ;
  1153.      %%
  1154. The functions `yylex', `yyerror' and `main' can be the same as before.
  1155.    There are two important new features shown in this code.
  1156.    In the second section (Bison declarations), `%left' declares token
  1157. types and says they are left-associative operators.  The declarations
  1158. `%left' and `%right' (right associativity) take the place of `%token'
  1159. which is used to declare a token type name without associativity.
  1160. (These tokens are single-character literals, which ordinarily don't
  1161. need to be declared.  We declare them here to specify the
  1162. associativity.)
  1163.    Operator precedence is determined by the line ordering of the
  1164. declarations; the higher the line number of the declaration (lower on
  1165. the page or screen), the higher the precedence.  Hence, exponentiation
  1166. has the highest precedence, unary minus (`NEG') is next, followed by
  1167. `*' and `/', and so on.  *Note Operator Precedence: Precedence.
  1168.    The other important new feature is the `%prec' in the grammar section
  1169. for the unary minus operator.  The `%prec' simply instructs Bison that
  1170. the rule `| '-' exp' has the same precedence as `NEG'--in this case the
  1171. next-to-highest.  *Note Context-Dependent Precedence: Contextual
  1172. Precedence.
  1173.    Here is a sample run of `calc.y':
  1174.      % calc
  1175.      4 + 4.5 - (34/(8*3+-3))
  1176.      6.880952381
  1177.      -56 + 2
  1178.      -54
  1179.      3 ^ 2
  1180.      9
  1181. File: bison,  Node: Simple Error Recovery,  Next: Multi-function Calc,  Prev: Infix Calc,  Up: Examples
  1182. Simple Error Recovery
  1183. =====================
  1184.    Up to this point, this manual has not addressed the issue of "error
  1185. recovery"--how to continue parsing after the parser detects a syntax
  1186. error.  All we have handled is error reporting with `yyerror'.  Recall
  1187. that by default `yyparse' returns after calling `yyerror'.  This means
  1188. that an erroneous input line causes the calculator program to exit.
  1189. Now we show how to rectify this deficiency.
  1190.    The Bison language itself includes the reserved word `error', which
  1191. may be included in the grammar rules.  In the example below it has been
  1192. added to one of the alternatives for `line':
  1193.      line:     '\n'
  1194.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  1195.              | error '\n' { yyerrok;                  }
  1196.      ;
  1197.    This addition to the grammar allows for simple error recovery in the
  1198. event of a parse error.  If an expression that cannot be evaluated is
  1199. read, the error will be recognized by the third rule for `line', and
  1200. parsing will continue.  (The `yyerror' function is still called upon to
  1201. print its message as well.)  The action executes the statement
  1202. `yyerrok', a macro defined automatically by Bison; its meaning is that
  1203. error recovery is complete (*note Error Recovery::.).  Note the
  1204. difference between `yyerrok' and `yyerror'; neither one is a misprint.
  1205.    This form of error recovery deals with syntax errors.  There are
  1206. other kinds of errors; for example, division by zero, which raises an
  1207. exception signal that is normally fatal.  A real calculator program
  1208. must handle this signal and use `longjmp' to return to `main' and
  1209. resume parsing input lines; it would also have to discard the rest of
  1210. the current line of input.  We won't discuss this issue further because
  1211. it is not specific to Bison programs.
  1212. File: bison,  Node: Multi-function Calc,  Next: Exercises,  Prev: Simple Error Recovery,  Up: Examples
  1213. Multi-Function Calculator: `mfcalc'
  1214. ===================================
  1215.    Now that the basics of Bison have been discussed, it is time to move
  1216. on to a more advanced problem.  The above calculators provided only five
  1217. functions, `+', `-', `*', `/' and `^'.  It would be nice to have a
  1218. calculator that provides other mathematical functions such as `sin',
  1219. `cos', etc.
  1220.    It is easy to add new operators to the infix calculator as long as
  1221. they are only single-character literals.  The lexical analyzer `yylex'
  1222. passes back all non-number characters as tokens, so new grammar rules
  1223. suffice for adding a new operator.  But we want something more
  1224. flexible: built-in functions whose syntax has this form:
  1225.      FUNCTION_NAME (ARGUMENT)
  1226. At the same time, we will add memory to the calculator, by allowing you
  1227. to create named variables, store values in them, and use them later.
  1228. Here is a sample session with the multi-function calculator:
  1229.      % acalc
  1230.      pi = 3.141592653589
  1231.      3.1415926536
  1232.      sin(pi)
  1233.      0.0000000000
  1234.      alpha = beta1 = 2.3
  1235.      2.3000000000
  1236.      alpha
  1237.      2.3000000000
  1238.      ln(alpha)
  1239.      0.8329091229
  1240.      exp(ln(beta1))
  1241.      2.3000000000
  1242.      %
  1243.    Note that multiple assignment and nested function calls are
  1244. permitted.
  1245. * Menu:
  1246. * Decl: Mfcalc Decl.      Bison declarations for multi-function calculator.
  1247. * Rules: Mfcalc Rules.    Grammar rules for the calculator.
  1248. * Symtab: Mfcalc Symtab.  Symbol table management subroutines.
  1249. File: bison,  Node: Mfcalc Decl,  Next: Mfcalc Rules,  Up: Multi-function Calc
  1250. Declarations for `mfcalc'
  1251. -------------------------
  1252.    Here are the C and Bison declarations for the multi-function
  1253. calculator.
  1254.      %{
  1255.      #include <math.h>  /* For math functions, cos(), sin(), etc. */
  1256.      #include "calc.h"  /* Contains definition of `symrec'        */
  1257.      %}
  1258.      %union {
  1259.      double     val;  /* For returning numbers.                   */
  1260.      symrec  *tptr;   /* For returning symbol-table pointers      */
  1261.      }
  1262.      
  1263.      %token <val>  NUM        /* Simple double precision number   */
  1264.      %token <tptr> VAR FNCT   /* Variable and Function            */
  1265.      %type  <val>  exp
  1266.      
  1267.      %right '='
  1268.      %left '-' '+'
  1269.      %left '*' '/'
  1270.      %left NEG     /* Negation--unary minus */
  1271.      %right '^'    /* Exponentiation        */
  1272.      
  1273.      /* Grammar follows */
  1274.      
  1275.      %%
  1276.    The above grammar introduces only two new features of the Bison
  1277. language.  These features allow semantic values to have various data
  1278. types (*note More Than One Value Type: Multiple Types.).
  1279.    The `%union' declaration specifies the entire list of possible types;
  1280. this is instead of defining `YYSTYPE'.  The allowable types are now
  1281. double-floats (for `exp' and `NUM') and pointers to entries in the
  1282. symbol table.  *Note The Collection of Value Types: Union Decl.
  1283.    Since values can now have various types, it is necessary to
  1284. associate a type with each grammar symbol whose semantic value is used.
  1285. These symbols are `NUM', `VAR', `FNCT', and `exp'.  Their declarations
  1286. are augmented with information about their data type (placed between
  1287. angle brackets).
  1288.    The Bison construct `%type' is used for declaring nonterminal
  1289. symbols, just as `%token' is used for declaring token types.  We have
  1290. not used `%type' before because nonterminal symbols are normally
  1291. declared implicitly by the rules that define them.  But `exp' must be
  1292. declared explicitly so we can specify its value type.  *Note
  1293. Nonterminal Symbols: Type Decl.
  1294. File: bison,  Node: Mfcalc Rules,  Next: Mfcalc Symtab,  Prev: Mfcalc Decl,  Up: Multi-function Calc
  1295. Grammar Rules for `mfcalc'
  1296. --------------------------
  1297.    Here are the grammar rules for the multi-function calculator.  Most
  1298. of them are copied directly from `calc'; three rules, those which
  1299. mention `VAR' or `FNCT', are new.
  1300.      input:   /* empty */
  1301.              | input line
  1302.      ;
  1303.      
  1304.      line:
  1305.                '\n'
  1306.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  1307.              | error '\n' { yyerrok;                  }
  1308.      ;
  1309.      
  1310.      exp:      NUM                { $$ = $1;                         }
  1311.              | VAR                { $$ = $1->value.var;              }
  1312.              | VAR '=' exp        { $$ = $3; $1->value.var = $3;     }
  1313.              | FNCT '(' exp ')'   { $$ = (*($1->value.fnctptr))($3); }
  1314.              | exp '+' exp        { $$ = $1 + $3;                    }
  1315.              | exp '-' exp        { $$ = $1 - $3;                    }
  1316.              | exp '*' exp        { $$ = $1 * $3;                    }
  1317.              | exp '/' exp        { $$ = $1 / $3;                    }
  1318.              | '-' exp  %prec NEG { $$ = -$2;                        }
  1319.              | exp '^' exp        { $$ = pow ($1, $3);               }
  1320.              | '(' exp ')'        { $$ = $2;                         }
  1321.      ;
  1322.      /* End of grammar */
  1323.      %%
  1324. File: bison,  Node: Mfcalc Symtab,  Prev: Mfcalc Rules,  Up: Multi-function Calc
  1325. The `mfcalc' Symbol Table
  1326. -------------------------
  1327.    The multi-function calculator requires a symbol table to keep track
  1328. of the names and meanings of variables and functions.  This doesn't
  1329. affect the grammar rules (except for the actions) or the Bison
  1330. declarations, but it requires some additional C functions for support.
  1331.    The symbol table itself consists of a linked list of records.  Its
  1332. definition, which is kept in the header `calc.h', is as follows.  It
  1333. provides for either functions or variables to be placed in the table.
  1334.      /* Data type for links in the chain of symbols.      */
  1335.      struct symrec
  1336.      {
  1337.        char *name;  /* name of symbol                     */
  1338.        int type;    /* type of symbol: either VAR or FNCT */
  1339.        union {
  1340.          double var;           /* value of a VAR          */
  1341.          double (*fnctptr)();  /* value of a FNCT         */
  1342.        } value;
  1343.        struct symrec *next;    /* link field              */
  1344.      };
  1345.      typedef struct symrec symrec;
  1346.      
  1347.      /* The symbol table: a chain of `struct symrec'.     */
  1348.      extern symrec *sym_table;
  1349.      
  1350.      symrec *putsym ();
  1351.      symrec *getsym ();
  1352.    The new version of `main' includes a call to `init_table', a
  1353. function that initializes the symbol table.  Here it is, and
  1354. `init_table' as well:
  1355.      #include <stdio.h>
  1356.      
  1357.      main ()
  1358.      {
  1359.        init_table ();
  1360.        yyparse ();
  1361.      }
  1362.      yyerror (s)  /* Called by yyparse on error */
  1363.           char *s;
  1364.      {
  1365.        printf ("%s\n", s);
  1366.      }
  1367.      
  1368.      struct init
  1369.      {
  1370.        char *fname;
  1371.        double (*fnct)();
  1372.      };
  1373.      struct init arith_fncts[]
  1374.        = {
  1375.            "sin", sin,
  1376.            "cos", cos,
  1377.            "atan", atan,
  1378.            "ln", log,
  1379.            "exp", exp,
  1380.            "sqrt", sqrt,
  1381.            0, 0
  1382.          };
  1383.      
  1384.      /* The symbol table: a chain of `struct symrec'.  */
  1385.      symrec *sym_table = (symrec *)0;
  1386.      init_table ()  /* puts arithmetic functions in table. */
  1387.      {
  1388.        int i;
  1389.        symrec *ptr;
  1390.        for (i = 0; arith_fncts[i].fname != 0; i++)
  1391.          {
  1392.            ptr = putsym (arith_fncts[i].fname, FNCT);
  1393.            ptr->value.fnctptr = arith_fncts[i].fnct;
  1394.          }
  1395.      }
  1396.    By simply editing the initialization list and adding the necessary
  1397. include files, you can add additional functions to the calculator.
  1398.    Two important functions allow look-up and installation of symbols in
  1399. the symbol table.  The function `putsym' is passed a name and the type
  1400. (`VAR' or `FNCT') of the object to be installed.  The object is linked
  1401. to the front of the list, and a pointer to the object is returned.  The
  1402. function `getsym' is passed the name of the symbol to look up.  If
  1403. found, a pointer to that symbol is returned; otherwise zero is returned.
  1404.      symrec *
  1405.      putsym (sym_name,sym_type)
  1406.           char *sym_name;
  1407.           int sym_type;
  1408.      {
  1409.        symrec *ptr;
  1410.        ptr = (symrec *) malloc (sizeof (symrec));
  1411.        ptr->name = (char *) malloc (strlen (sym_name) + 1);
  1412.        strcpy (ptr->name,sym_name);
  1413.        ptr->type = sym_type;
  1414.        ptr->value.var = 0; /* set value to 0 even if fctn.  */
  1415.        ptr->next = (struct symrec *)sym_table;
  1416.        sym_table = ptr;
  1417.        return ptr;
  1418.      }
  1419.      
  1420.      symrec *
  1421.      getsym (sym_name)
  1422.           char *sym_name;
  1423.      {
  1424.        symrec *ptr;
  1425.        for (ptr = sym_table; ptr != (symrec *) 0;
  1426.             ptr = (symrec *)ptr->next)
  1427.          if (strcmp (ptr->name,sym_name) == 0)
  1428.            return ptr;
  1429.        return 0;
  1430.      }
  1431.    The function `yylex' must now recognize variables, numeric values,
  1432. and the single-character arithmetic operators.  Strings of alphanumeric
  1433. characters with a leading nondigit are recognized as either variables or
  1434. functions depending on what the symbol table says about them.
  1435.    The string is passed to `getsym' for look up in the symbol table.  If
  1436. the name appears in the table, a pointer to its location and its type
  1437. (`VAR' or `FNCT') is returned to `yyparse'.  If it is not already in
  1438. the table, then it is installed as a `VAR' using `putsym'.  Again, a
  1439. pointer and its type (which must be `VAR') is returned to `yyparse'.
  1440.    No change is needed in the handling of numeric values and arithmetic
  1441. operators in `yylex'.
  1442.      #include <ctype.h>
  1443.      yylex ()
  1444.      {
  1445.        int c;
  1446.      
  1447.        /* Ignore whitespace, get first nonwhite character.  */
  1448.        while ((c = getchar ()) == ' ' || c == '\t');
  1449.      
  1450.        if (c == EOF)
  1451.          return 0;
  1452.      /* Char starts a number => parse the number.         */
  1453.        if (c == '.' || isdigit (c))
  1454.          {
  1455.            ungetc (c, stdin);
  1456.            scanf ("%lf", &yylval.val);
  1457.            return NUM;
  1458.          }
  1459.      /* Char starts an identifier => read the name.       */
  1460.        if (isalpha (c))
  1461.          {
  1462.            symrec *s;
  1463.            static char *symbuf = 0;
  1464.            static int length = 0;
  1465.            int i;
  1466.      /* Initially make the buffer long enough
  1467.               for a 40-character symbol name.  */
  1468.            if (length == 0)
  1469.              length = 40, symbuf = (char *)malloc (length + 1);
  1470.      
  1471.            i = 0;
  1472.            do
  1473.      {
  1474.                /* If buffer is full, make it bigger.        */
  1475.                if (i == length)
  1476.                  {
  1477.                    length *= 2;
  1478.                    symbuf = (char *)realloc (symbuf, length + 1);
  1479.                  }
  1480.                /* Add this character to the buffer.         */
  1481.                symbuf[i++] = c;
  1482.                /* Get another character.                    */
  1483.                c = getchar ();
  1484.              }
  1485.      while (c != EOF && isalnum (c));
  1486.      
  1487.            ungetc (c, stdin);
  1488.            symbuf[i] = '\0';
  1489.      s = getsym (symbuf);
  1490.            if (s == 0)
  1491.              s = putsym (symbuf, VAR);
  1492.            yylval.tptr = s;
  1493.            return s->type;
  1494.          }
  1495.      
  1496.        /* Any other character is a token by itself.        */
  1497.        return c;
  1498.      }
  1499.    This program is both powerful and flexible. You may easily add new
  1500. functions, and it is a simple job to modify this code to install
  1501. predefined variables such as `pi' or `e' as well.
  1502. File: bison,  Node: Exercises,  Prev: Multi-function Calc,  Up: Examples
  1503. Exercises
  1504. =========
  1505.   1. Add some new functions from `math.h' to the initialization list.
  1506.   2. Add another array that contains constants and their values.  Then
  1507.      modify `init_table' to add these constants to the symbol table.
  1508.      It will be easiest to give the constants type `VAR'.
  1509.   3. Make the program report an error if the user refers to an
  1510.      uninitialized variable in any way except to store a value in it.
  1511. File: bison,  Node: Grammar File,  Next: Interface,  Prev: Examples,  Up: Top
  1512. Bison Grammar Files
  1513. *******************
  1514.    Bison takes as input a context-free grammar specification and
  1515. produces a C-language function that recognizes correct instances of the
  1516. grammar.
  1517.    The Bison grammar input file conventionally has a name ending in
  1518. `.y'.
  1519. * Menu:
  1520. * Grammar Outline::   Overall layout of the grammar file.
  1521. * Symbols::           Terminal and nonterminal symbols.
  1522. * Rules::             How to write grammar rules.
  1523. * Recursion::         Writing recursive rules.
  1524. * Semantics::         Semantic values and actions.
  1525. * Declarations::      All kinds of Bison declarations are described here.
  1526. * Multiple Parsers::  Putting more than one Bison parser in one program.
  1527. File: bison,  Node: Grammar Outline,  Next: Symbols,  Up: Grammar File
  1528. Outline of a Bison Grammar
  1529. ==========================
  1530.    A Bison grammar file has four main sections, shown here with the
  1531. appropriate delimiters:
  1532.      %{
  1533.      C DECLARATIONS
  1534.      %}
  1535.      
  1536.      BISON DECLARATIONS
  1537.      
  1538.      %%
  1539.      GRAMMAR RULES
  1540.      %%
  1541.      
  1542.      ADDITIONAL C CODE
  1543.    Comments enclosed in `/* ... */' may appear in any of the sections.
  1544. * Menu:
  1545. * C Declarations::    Syntax and usage of the C declarations section.
  1546. * Bison Declarations::  Syntax and usage of the Bison declarations section.
  1547. * Grammar Rules::     Syntax and usage of the grammar rules section.
  1548. * C Code::            Syntax and usage of the additional C code section.
  1549. File: bison,  Node: C Declarations,  Next: Bison Declarations,  Up: Grammar Outline
  1550. The C Declarations Section
  1551. --------------------------
  1552.    The C DECLARATIONS section contains macro definitions and
  1553. declarations of functions and variables that are used in the actions in
  1554. the grammar rules.  These are copied to the beginning of the parser
  1555. file so that they precede the definition of `yyparse'.  You can use
  1556. `#include' to get the declarations from a header file.  If you don't
  1557. need any C declarations, you may omit the `%{' and `%}' delimiters that
  1558. bracket this section.
  1559. File: bison,  Node: Bison Declarations,  Next: Grammar Rules,  Prev: C Declarations,  Up: Grammar Outline
  1560. The Bison Declarations Section
  1561. ------------------------------
  1562.    The BISON DECLARATIONS section contains declarations that define
  1563. terminal and nonterminal symbols, specify precedence, and so on.  In
  1564. some simple grammars you may not need any declarations.  *Note Bison
  1565. Declarations: Declarations.
  1566. File: bison,  Node: Grammar Rules,  Next: C Code,  Prev: Bison Declarations,  Up: Grammar Outline
  1567. The Grammar Rules Section
  1568. -------------------------
  1569.    The "grammar rules" section contains one or more Bison grammar
  1570. rules, and nothing else.  *Note Syntax of Grammar Rules: Rules.
  1571.    There must always be at least one grammar rule, and the first `%%'
  1572. (which precedes the grammar rules) may never be omitted even if it is
  1573. the first thing in the file.
  1574. File: bison,  Node: C Code,  Prev: Grammar Rules,  Up: Grammar Outline
  1575. The Additional C Code Section
  1576. -----------------------------
  1577.    The ADDITIONAL C CODE section is copied verbatim to the end of the
  1578. parser file, just as the C DECLARATIONS section is copied to the
  1579. beginning.  This is the most convenient place to put anything that you
  1580. want to have in the parser file but which need not come before the
  1581. definition of `yyparse'.  For example, the definitions of `yylex' and
  1582. `yyerror' often go here.  *Note Parser C-Language Interface: Interface.
  1583.    If the last section is empty, you may omit the `%%' that separates it
  1584. from the grammar rules.
  1585.    The Bison parser itself contains many static variables whose names
  1586. start with `yy' and many macros whose names start with `YY'.  It is a
  1587. good idea to avoid using any such names (except those documented in this
  1588. manual) in the additional C code section of the grammar file.
  1589. File: bison,  Node: Symbols,  Next: Rules,  Prev: Grammar Outline,  Up: Grammar File
  1590. Symbols, Terminal and Nonterminal
  1591. =================================
  1592.    "Symbols" in Bison grammars represent the grammatical classifications
  1593. of the language.
  1594.    A "terminal symbol" (also known as a "token type") represents a
  1595. class of syntactically equivalent tokens.  You use the symbol in grammar
  1596. rules to mean that a token in that class is allowed.  The symbol is
  1597. represented in the Bison parser by a numeric code, and the `yylex'
  1598. function returns a token type code to indicate what kind of token has
  1599. been read.  You don't need to know what the code value is; you can use
  1600. the symbol to stand for it.
  1601.    A "nonterminal symbol" stands for a class of syntactically equivalent
  1602. groupings.  The symbol name is used in writing grammar rules.  By
  1603. convention, it should be all lower case.
  1604.    Symbol names can contain letters, digits (not at the beginning),
  1605. underscores and periods.  Periods make sense only in nonterminals.
  1606.    There are two ways of writing terminal symbols in the grammar:
  1607.    * A "named token type" is written with an identifier, like an
  1608.      identifier in C.  By convention, it should be all upper case.  Each
  1609.      such name must be defined with a Bison declaration such as
  1610.      `%token'.  *Note Token Type Names: Token Decl.
  1611.    * A "character token type" (or "literal token") is written in the
  1612.      grammar using the same syntax used in C for character constants;
  1613.      for example, `'+'' is a character token type.  A character token
  1614.      type doesn't need to be declared unless you need to specify its
  1615.      semantic value data type (*note Data Types of Semantic Values:
  1616.      Value Type.), associativity, or precedence (*note Operator
  1617.      Precedence: Precedence.).
  1618.      By convention, a character token type is used only to represent a
  1619.      token that consists of that particular character.  Thus, the token
  1620.      type `'+'' is used to represent the character `+' as a token.
  1621.      Nothing enforces this convention, but if you depart from it, your
  1622.      program will confuse other readers.
  1623.      All the usual escape sequences used in character literals in C can
  1624.      be used in Bison as well, but you must not use the null character
  1625.      as a character literal because its ASCII code, zero, is the code
  1626.      `yylex' returns for end-of-input (*note Calling Convention for
  1627.      `yylex': Calling Convention.).
  1628.    How you choose to write a terminal symbol has no effect on its
  1629. grammatical meaning.  That depends only on where it appears in rules and
  1630. on when the parser function returns that symbol.
  1631.    The value returned by `yylex' is always one of the terminal symbols
  1632. (or 0 for end-of-input).  Whichever way you write the token type in the
  1633. grammar rules, you write it the same way in the definition of `yylex'.
  1634. The numeric code for a character token type is simply the ASCII code for
  1635. the character, so `yylex' can use the identical character constant to
  1636. generate the requisite code.  Each named token type becomes a C macro in
  1637. the parser file, so `yylex' can use the name to stand for the code.
  1638. (This is why periods don't make sense in terminal symbols.) *Note
  1639. Calling Convention for `yylex': Calling Convention.
  1640.    If `yylex' is defined in a separate file, you need to arrange for the
  1641. token-type macro definitions to be available there.  Use the `-d'
  1642. option when you run Bison, so that it will write these macro definitions
  1643. into a separate header file `NAME.tab.h' which you can include in the
  1644. other source files that need it.  *Note Invoking Bison: Invocation.
  1645.    The symbol `error' is a terminal symbol reserved for error recovery
  1646. (*note Error Recovery::.); you shouldn't use it for any other purpose.
  1647. In particular, `yylex' should never return this value.
  1648. File: bison,  Node: Rules,  Next: Recursion,  Prev: Symbols,  Up: Grammar File
  1649. Syntax of Grammar Rules
  1650. =======================
  1651.    A Bison grammar rule has the following general form:
  1652.      RESULT: COMPONENTS...
  1653.              ;
  1654. where RESULT is the nonterminal symbol that this rule describes and
  1655. COMPONENTS are various terminal and nonterminal symbols that are put
  1656. together by this rule (*note Symbols::.).
  1657.    For example,
  1658.      exp:      exp '+' exp
  1659.              ;
  1660. says that two groupings of type `exp', with a `+' token in between, can
  1661. be combined into a larger grouping of type `exp'.
  1662.    Whitespace in rules is significant only to separate symbols.  You
  1663. can add extra whitespace as you wish.
  1664.    Scattered among the components can be ACTIONS that determine the
  1665. semantics of the rule.  An action looks like this:
  1666.      {C STATEMENTS}
  1667. Usually there is only one action and it follows the components.  *Note
  1668. Actions::.
  1669.    Multiple rules for the same RESULT can be written separately or can
  1670. be joined with the vertical-bar character `|' as follows:
  1671.      RESULT:   RULE1-COMPONENTS...
  1672.              | RULE2-COMPONENTS...
  1673.              ...
  1674.              ;
  1675. They are still considered distinct rules even when joined in this way.
  1676.    If COMPONENTS in a rule is empty, it means that RESULT can match the
  1677. empty string.  For example, here is how to define a comma-separated
  1678. sequence of zero or more `exp' groupings:
  1679.      expseq:   /* empty */
  1680.              | expseq1
  1681.              ;
  1682.      
  1683.      expseq1:  exp
  1684.              | expseq1 ',' exp
  1685.              ;
  1686. It is customary to write a comment `/* empty */' in each rule with no
  1687. components.
  1688. File: bison,  Node: Recursion,  Next: Semantics,  Prev: Rules,  Up: Grammar File
  1689. Recursive Rules
  1690. ===============
  1691.    A rule is called "recursive" when its RESULT nonterminal appears
  1692. also on its right hand side.  Nearly all Bison grammars need to use
  1693. recursion, because that is the only way to define a sequence of any
  1694. number of somethings.  Consider this recursive definition of a
  1695. comma-separated sequence of one or more expressions:
  1696.      expseq1:  exp
  1697.              | expseq1 ',' exp
  1698.              ;
  1699. Since the recursive use of `expseq1' is the leftmost symbol in the
  1700. right hand side, we call this "left recursion".  By contrast, here the
  1701. same construct is defined using "right recursion":
  1702.      expseq1:  exp
  1703.              | exp ',' expseq1
  1704.              ;
  1705. Any kind of sequence can be defined using either left recursion or
  1706. right recursion, but you should always use left recursion, because it
  1707. can parse a sequence of any number of elements with bounded stack
  1708. space.  Right recursion uses up space on the Bison stack in proportion
  1709. to the number of elements in the sequence, because all the elements
  1710. must be shifted onto the stack before the rule can be applied even
  1711. once.  *Note The Bison Parser Algorithm: Algorithm, for further
  1712. explanation of this.
  1713.    "Indirect" or "mutual" recursion occurs when the result of the rule
  1714. does not appear directly on its right hand side, but does appear in
  1715. rules for other nonterminals which do appear on its right hand side.
  1716.    For example:
  1717.      expr:     primary
  1718.              | primary '+' primary
  1719.              ;
  1720.      
  1721.      primary:  constant
  1722.              | '(' expr ')'
  1723.              ;
  1724. defines two mutually-recursive nonterminals, since each refers to the
  1725. other.
  1726. File: bison,  Node: Semantics,  Next: Declarations,  Prev: Recursion,  Up: Grammar File
  1727. Defining Language Semantics
  1728. ===========================
  1729.    The grammar rules for a language determine only the syntax.  The
  1730. semantics are determined by the semantic values associated with various
  1731. tokens and groupings, and by the actions taken when various groupings
  1732. are recognized.
  1733.    For example, the calculator calculates properly because the value
  1734. associated with each expression is the proper number; it adds properly
  1735. because the action for the grouping `X + Y' is to add the numbers
  1736. associated with X and Y.
  1737. * Menu:
  1738. * Value Type::        Specifying one data type for all semantic values.
  1739. * Multiple Types::    Specifying several alternative data types.
  1740. * Actions::           An action is the semantic definition of a grammar rule.
  1741. * Action Types::      Specifying data types for actions to operate on.
  1742. * Mid-Rule Actions::  Most actions go at the end of a rule.
  1743.                       This says when, why and how to use the exceptional
  1744.                         action in the middle of a rule.
  1745. File: bison,  Node: Value Type,  Next: Multiple Types,  Up: Semantics
  1746. Data Types of Semantic Values
  1747. -----------------------------
  1748.    In a simple program it may be sufficient to use the same data type
  1749. for the semantic values of all language constructs.  This was true in
  1750. the RPN and infix calculator examples (*note Reverse Polish Notation
  1751. Calculator: RPN Calc.).
  1752.    Bison's default is to use type `int' for all semantic values.  To
  1753. specify some other type, define `YYSTYPE' as a macro, like this:
  1754.      #define YYSTYPE double
  1755. This macro definition must go in the C declarations section of the
  1756. grammar file (*note Outline of a Bison Grammar: Grammar Outline.).
  1757. File: bison,  Node: Multiple Types,  Next: Actions,  Prev: Value Type,  Up: Semantics
  1758. More Than One Value Type
  1759. ------------------------
  1760.    In most programs, you will need different data types for different
  1761. kinds of tokens and groupings.  For example, a numeric constant may
  1762. need type `int' or `long', while a string constant needs type `char *',
  1763. and an identifier might need a pointer to an entry in the symbol table.
  1764.    To use more than one data type for semantic values in one parser,
  1765. Bison requires you to do two things:
  1766.    * Specify the entire collection of possible data types, with the
  1767.      `%union' Bison declaration (*note The Collection of Value Types:
  1768.      Union Decl.).
  1769.    * Choose one of those types for each symbol (terminal or nonterminal)
  1770.      for which semantic values are used.  This is done for tokens with
  1771.      the `%token' Bison declaration (*note Token Type Names: Token
  1772.      Decl.) and for groupings with the `%type' Bison declaration (*note
  1773.      Nonterminal Symbols: Type Decl.).
  1774. File: bison,  Node: Actions,  Next: Action Types,  Prev: Multiple Types,  Up: Semantics
  1775. Actions
  1776. -------
  1777.    An action accompanies a syntactic rule and contains C code to be
  1778. executed each time an instance of that rule is recognized.  The task of
  1779. most actions is to compute a semantic value for the grouping built by
  1780. the rule from the semantic values associated with tokens or smaller
  1781. groupings.
  1782.    An action consists of C statements surrounded by braces, much like a
  1783. compound statement in C.  It can be placed at any position in the rule;
  1784. it is executed at that position.  Most rules have just one action at
  1785. the end of the rule, following all the components.  Actions in the
  1786. middle of a rule are tricky and used only for special purposes (*note
  1787. Actions in Mid-Rule: Mid-Rule Actions.).
  1788.    The C code in an action can refer to the semantic values of the
  1789. components matched by the rule with the construct `$N', which stands for
  1790. the value of the Nth component.  The semantic value for the grouping
  1791. being constructed is `$$'.  (Bison translates both of these constructs
  1792. into array element references when it copies the actions into the parser
  1793. file.)
  1794.    Here is a typical example:
  1795.      exp:    ...
  1796.              | exp '+' exp
  1797.                  { $$ = $1 + $3; }
  1798. This rule constructs an `exp' from two smaller `exp' groupings
  1799. connected by a plus-sign token.  In the action, `$1' and `$3' refer to
  1800. the semantic values of the two component `exp' groupings, which are the
  1801. first and third symbols on the right hand side of the rule.  The sum is
  1802. stored into `$$' so that it becomes the semantic value of the
  1803. addition-expression just recognized by the rule.  If there were a
  1804. useful semantic value associated with the `+' token, it could be
  1805. referred to as `$2'.
  1806.    If you don't specify an action for a rule, Bison supplies a default:
  1807. `$$ = $1'.  Thus, the value of the first symbol in the rule becomes the
  1808. value of the whole rule.  Of course, the default rule is valid only if
  1809. the two data types match.  There is no meaningful default action for an
  1810. empty rule; every empty rule must have an explicit action unless the
  1811. rule's value does not matter.
  1812.    `$N' with N zero or negative is allowed for reference to tokens and
  1813. groupings on the stack *before* those that match the current rule.
  1814. This is a very risky practice, and to use it reliably you must be
  1815. certain of the context in which the rule is applied.  Here is a case in
  1816. which you can use this reliably:
  1817.      foo:      expr bar '+' expr  { ... }
  1818.              | expr bar '-' expr  { ... }
  1819.              ;
  1820.      
  1821.      bar:      /* empty */
  1822.              { previous_expr = $0; }
  1823.              ;
  1824.    As long as `bar' is used only in the fashion shown here, `$0' always
  1825. refers to the `expr' which precedes `bar' in the definition of `foo'.
  1826. File: bison,  Node: Action Types,  Next: Mid-Rule Actions,  Prev: Actions,  Up: Semantics
  1827. Data Types of Values in Actions
  1828. -------------------------------
  1829.    If you have chosen a single data type for semantic values, the `$$'
  1830. and `$N' constructs always have that data type.
  1831.    If you have used `%union' to specify a variety of data types, then
  1832. you must declare a choice among these types for each terminal or
  1833. nonterminal symbol that can have a semantic value.  Then each time you
  1834. use `$$' or `$N', its data type is determined by which symbol it refers
  1835. to in the rule.  In this example,
  1836.      exp:    ...
  1837.              | exp '+' exp
  1838.                  { $$ = $1 + $3; }
  1839. `$1' and `$3' refer to instances of `exp', so they all have the data
  1840. type declared for the nonterminal symbol `exp'.  If `$2' were used, it
  1841. would have the data type declared for the terminal symbol `'+'',
  1842. whatever that might be.
  1843.    Alternatively, you can specify the data type when you refer to the
  1844. value, by inserting `<TYPE>' after the `$' at the beginning of the
  1845. reference.  For example, if you have defined types as shown here:
  1846.      %union {
  1847.        int itype;
  1848.        double dtype;
  1849.      }
  1850. then you can write `$<itype>1' to refer to the first subunit of the
  1851. rule as an integer, or `$<dtype>1' to refer to it as a double.
  1852. File: bison,  Node: Mid-Rule Actions,  Prev: Action Types,  Up: Semantics
  1853. Actions in Mid-Rule
  1854. -------------------
  1855.    Occasionally it is useful to put an action in the middle of a rule.
  1856. These actions are written just like usual end-of-rule actions, but they
  1857. are executed before the parser even recognizes the following components.
  1858.    A mid-rule action may refer to the components preceding it using
  1859. `$N', but it may not refer to subsequent components because it is run
  1860. before they are parsed.
  1861.    The mid-rule action itself counts as one of the components of the
  1862. rule.  This makes a difference when there is another action later in
  1863. the same rule (and usually there is another at the end): you have to
  1864. count the actions along with the symbols when working out which number
  1865. N to use in `$N'.
  1866.    The mid-rule action can also have a semantic value.  The action can
  1867. set its value with an assignment to `$$', and actions later in the rule
  1868. can refer to the value using `$N'.  Since there is no symbol to name
  1869. the action, there is no way to declare a data type for the value in
  1870. advance, so you must use the `$<...>' construct to specify a data type
  1871. each time you refer to this value.
  1872.    There is no way to set the value of the entire rule with a mid-rule
  1873. action, because assignments to `$$' do not have that effect.  The only
  1874. way to set the value for the entire rule is with an ordinary action at
  1875. the end of the rule.
  1876.    Here is an example from a hypothetical compiler, handling a `let'
  1877. statement that looks like `let (VARIABLE) STATEMENT' and serves to
  1878. create a variable named VARIABLE temporarily for the duration of
  1879. STATEMENT.  To parse this construct, we must put VARIABLE into the
  1880. symbol table while STATEMENT is parsed, then remove it afterward.  Here
  1881. is how it is done:
  1882.      stmt:   LET '(' var ')'
  1883.                      { $<context>$ = push_context ();
  1884.                        declare_variable ($3); }
  1885.              stmt    { $$ = $6;
  1886.                        pop_context ($<context>5); }
  1887. As soon as `let (VARIABLE)' has been recognized, the first action is
  1888. run.  It saves a copy of the current semantic context (the list of
  1889. accessible variables) as its semantic value, using alternative
  1890. `context' in the data-type union.  Then it calls `declare_variable' to
  1891. add the new variable to that list.  Once the first action is finished,
  1892. the embedded statement `stmt' can be parsed.  Note that the mid-rule
  1893. action is component number 5, so the `stmt' is component number 6.
  1894.    After the embedded statement is parsed, its semantic value becomes
  1895. the value of the entire `let'-statement.  Then the semantic value from
  1896. the earlier action is used to restore the prior list of variables.  This
  1897. removes the temporary `let'-variable from the list so that it won't
  1898. appear to exist while the rest of the program is parsed.
  1899.    Taking action before a rule is completely recognized often leads to
  1900. conflicts since the parser must commit to a parse in order to execute
  1901. the action.  For example, the following two rules, without mid-rule
  1902. actions, can coexist in a working parser because the parser can shift
  1903. the open-brace token and look at what follows before deciding whether
  1904. there is a declaration or not:
  1905.      compound: '{' declarations statements '}'
  1906.              | '{' statements '}'
  1907.              ;
  1908. But when we add a mid-rule action as follows, the rules become
  1909. nonfunctional:
  1910.      compound: { prepare_for_local_variables (); }
  1911.                '{' declarations statements '}'
  1912.              | '{' statements '}'
  1913.              ;
  1914. Now the parser is forced to decide whether to run the mid-rule action
  1915. when it has read no farther than the open-brace.  In other words, it
  1916. must commit to using one rule or the other, without sufficient
  1917. information to do it correctly.  (The open-brace token is what is called
  1918. the "look-ahead" token at this time, since the parser is still deciding
  1919. what to do about it.  *Note Look-Ahead Tokens: Look-Ahead.)
  1920.    You might think that you could correct the problem by putting
  1921. identical actions into the two rules, like this:
  1922.      compound: { prepare_for_local_variables (); }
  1923.                '{' declarations statements '}'
  1924.              | { prepare_for_local_variables (); }
  1925.                '{' statements '}'
  1926.              ;
  1927. But this does not help, because Bison does not realize that the two
  1928. actions are identical.  (Bison never tries to understand the C code in
  1929. an action.)
  1930.    If the grammar is such that a declaration can be distinguished from a
  1931. statement by the first token (which is true in C), then one solution
  1932. which does work is to put the action after the open-brace, like this:
  1933.      compound: '{' { prepare_for_local_variables (); }
  1934.                declarations statements '}'
  1935.              | '{' statements '}'
  1936.              ;
  1937. Now the first token of the following declaration or statement, which
  1938. would in any case tell Bison which rule to use, can still do so.
  1939.    Another solution is to bury the action inside a nonterminal symbol
  1940. which serves as a subroutine:
  1941.      subroutine: /* empty */
  1942.                { prepare_for_local_variables (); }
  1943.              ;
  1944.      
  1945.      compound: subroutine
  1946.                '{' declarations statements '}'
  1947.              | subroutine
  1948.                '{' statements '}'
  1949.              ;
  1950. Now Bison can execute the action in the rule for `subroutine' without
  1951. deciding which rule for `compound' it will eventually use.  Note that
  1952. the action is now at the end of its rule.  Any mid-rule action can be
  1953. converted to an end-of-rule action in this way, and this is what Bison
  1954. actually does to implement mid-rule actions.
  1955. File: bison,  Node: Declarations,  Next: Multiple Parsers,  Prev: Semantics,  Up: Grammar File
  1956. Bison Declarations
  1957. ==================
  1958.    The "Bison declarations" section of a Bison grammar defines the
  1959. symbols used in formulating the grammar and the data types of semantic
  1960. values.  *Note Symbols::.
  1961.    All token type names (but not single-character literal tokens such as
  1962. `'+'' and `'*'') must be declared.  Nonterminal symbols must be
  1963. declared if you need to specify which data type to use for the semantic
  1964. value (*note More Than One Value Type: Multiple Types.).
  1965.    The first rule in the file also specifies the start symbol, by
  1966. default.  If you want some other symbol to be the start symbol, you
  1967. must declare it explicitly (*note Languages and Context-Free Grammars:
  1968. Language and Grammar.).
  1969. * Menu:
  1970. * Token Decl::        Declaring terminal symbols.
  1971. * Precedence Decl::   Declaring terminals with precedence and associativity.
  1972. * Union Decl::        Declaring the set of all semantic value types.
  1973. * Type Decl::         Declaring the choice of type for a nonterminal symbol.
  1974. * Expect Decl::       Suppressing warnings about shift/reduce conflicts.
  1975. * Start Decl::        Specifying the start symbol.
  1976. * Pure Decl::         Requesting a reentrant parser.
  1977. * Decl Summary::      Table of all Bison declarations.
  1978. File: bison,  Node: Token Decl,  Next: Precedence Decl,  Up: Declarations
  1979. Token Type Names
  1980. ----------------
  1981.    The basic way to declare a token type name (terminal symbol) is as
  1982. follows:
  1983.      %token NAME
  1984.    Bison will convert this into a `#define' directive in the parser, so
  1985. that the function `yylex' (if it is in this file) can use the name NAME
  1986. to stand for this token type's code.
  1987.    Alternatively, you can use `%left', `%right', or `%nonassoc' instead
  1988. of `%token', if you wish to specify precedence.  *Note Operator
  1989. Precedence: Precedence Decl.
  1990.    You can explicitly specify the numeric code for a token type by
  1991. appending an integer value in the field immediately following the token
  1992. name:
  1993.      %token NUM 300
  1994. It is generally best, however, to let Bison choose the numeric codes for
  1995. all token types.  Bison will automatically select codes that don't
  1996. conflict with each other or with ASCII characters.
  1997.    In the event that the stack type is a union, you must augment the
  1998. `%token' or other token declaration to include the data type
  1999. alternative delimited by angle-brackets (*note More Than One Value
  2000. Type: Multiple Types.).
  2001.    For example:
  2002.      %union {              /* define stack type */
  2003.        double val;
  2004.        symrec *tptr;
  2005.      }
  2006.      %token <val> NUM      /* define token NUM and its type */
  2007. File: bison,  Node: Precedence Decl,  Next: Union Decl,  Prev: Token Decl,  Up: Declarations
  2008. Operator Precedence
  2009. -------------------
  2010.    Use the `%left', `%right' or `%nonassoc' declaration to declare a
  2011. token and specify its precedence and associativity, all at once.  These
  2012. are called "precedence declarations".  *Note Operator Precedence:
  2013. Precedence, for general information on operator precedence.
  2014.    The syntax of a precedence declaration is the same as that of
  2015. `%token': either
  2016.      %left SYMBOLS...
  2017.      %left <TYPE> SYMBOLS...
  2018.    And indeed any of these declarations serves the purposes of `%token'.
  2019. But in addition, they specify the associativity and relative precedence
  2020. for all the SYMBOLS:
  2021.    * The associativity of an operator OP determines how repeated uses
  2022.      of the operator nest: whether `X OP Y OP Z' is parsed by grouping
  2023.      X with Y first or by grouping Y with Z first.  `%left' specifies
  2024.      left-associativity (grouping X with Y first) and `%right'
  2025.      specifies right-associativity (grouping Y with Z first).
  2026.      `%nonassoc' specifies no associativity, which means that `X OP Y
  2027.      OP Z' is considered a syntax error.
  2028.    * The precedence of an operator determines how it nests with other
  2029.      operators.  All the tokens declared in a single precedence
  2030.      declaration have equal precedence and nest together according to
  2031.      their associativity.  When two tokens declared in different
  2032.      precedence declarations associate, the one declared later has the
  2033.      higher precedence and is grouped first.
  2034. File: bison,  Node: Union Decl,  Next: Type Decl,  Prev: Precedence Decl,  Up: Declarations
  2035. The Collection of Value Types
  2036. -----------------------------
  2037.    The `%union' declaration specifies the entire collection of possible
  2038. data types for semantic values.  The keyword `%union' is followed by a
  2039. pair of braces containing the same thing that goes inside a `union' in
  2040.    For example:
  2041.      %union {
  2042.        double val;
  2043.        symrec *tptr;
  2044.      }
  2045. This says that the two alternative types are `double' and `symrec *'.
  2046. They are given names `val' and `tptr'; these names are used in the
  2047. `%token' and `%type' declarations to pick one of the types for a
  2048. terminal or nonterminal symbol (*note Nonterminal Symbols: Type Decl.).
  2049.    Note that, unlike making a `union' declaration in C, you do not write
  2050. a semicolon after the closing brace.
  2051. File: bison,  Node: Type Decl,  Next: Expect Decl,  Prev: Union Decl,  Up: Declarations
  2052. Nonterminal Symbols
  2053. -------------------
  2054. When you use `%union' to specify multiple value types, you must declare
  2055. the value type of each nonterminal symbol for which values are used.
  2056. This is done with a `%type' declaration, like this:
  2057.      %type <TYPE> NONTERMINAL...
  2058. Here NONTERMINAL is the name of a nonterminal symbol, and TYPE is the
  2059. name given in the `%union' to the alternative that you want (*note The
  2060. Collection of Value Types: Union Decl.).  You can give any number of
  2061. nonterminal symbols in the same `%type' declaration, if they have the
  2062. same value type.  Use spaces to separate the symbol names.
  2063. File: bison,  Node: Expect Decl,  Next: Start Decl,  Prev: Type Decl,  Up: Declarations
  2064. Suppressing Conflict Warnings
  2065. -----------------------------
  2066.    Bison normally warns if there are any conflicts in the grammar
  2067. (*note Shift/Reduce Conflicts: Shift/Reduce.), but most real grammars
  2068. have harmless shift/reduce conflicts which are resolved in a
  2069. predictable way and would be difficult to eliminate.  It is desirable
  2070. to suppress the warning about these conflicts unless the number of
  2071. conflicts changes.  You can do this with the `%expect' declaration.
  2072.    The declaration looks like this:
  2073.      %expect N
  2074.    Here N is a decimal integer.  The declaration says there should be no
  2075. warning if there are N shift/reduce conflicts and no reduce/reduce
  2076. conflicts.  The usual warning is given if there are either more or fewer
  2077. conflicts, or if there are any reduce/reduce conflicts.
  2078.    In general, using `%expect' involves these steps:
  2079.    * Compile your grammar without `%expect'.  Use the `-v' option to
  2080.      get a verbose list of where the conflicts occur.  Bison will also
  2081.      print the number of conflicts.
  2082.    * Check each of the conflicts to make sure that Bison's default
  2083.      resolution is what you really want.  If not, rewrite the grammar
  2084.      and go back to the beginning.
  2085.    * Add an `%expect' declaration, copying the number N from the number
  2086.      which Bison printed.
  2087.    Now Bison will stop annoying you about the conflicts you have
  2088. checked, but it will warn you again if changes in the grammar result in
  2089. additional conflicts.
  2090. File: bison,  Node: Start Decl,  Next: Pure Decl,  Prev: Expect Decl,  Up: Declarations
  2091. The Start-Symbol
  2092. ----------------
  2093.    Bison assumes by default that the start symbol for the grammar is
  2094. the first nonterminal specified in the grammar specification section.
  2095. The programmer may override this restriction with the `%start'
  2096. declaration as follows:
  2097.      %start SYMBOL
  2098. File: bison,  Node: Pure Decl,  Next: Decl Summary,  Prev: Start Decl,  Up: Declarations
  2099. A Pure (Reentrant) Parser
  2100. -------------------------
  2101.    A "reentrant" program is one which does not alter in the course of
  2102. execution; in other words, it consists entirely of "pure" (read-only)
  2103. code.  Reentrancy is important whenever asynchronous execution is
  2104. possible; for example, a nonreentrant program may not be safe to call
  2105. from a signal handler.  In systems with multiple threads of control, a
  2106. nonreentrant program must be called only within interlocks.
  2107.    The Bison parser is not normally a reentrant program, because it uses
  2108. statically allocated variables for communication with `yylex'.  These
  2109. variables include `yylval' and `yylloc'.
  2110.    The Bison declaration `%pure_parser' says that you want the parser
  2111. to be reentrant.  It looks like this:
  2112.      %pure_parser
  2113.    The effect is that the two communication variables become local
  2114. variables in `yyparse', and a different calling convention is used for
  2115. the lexical analyzer function `yylex'.  *Note Calling for Pure Parsers:
  2116. Pure Calling, for the details of this.  The variable `yynerrs' also
  2117. becomes local in `yyparse' (*note The Error Reporting Function
  2118. `yyerror': Error Reporting.).  The convention for calling `yyparse'
  2119. itself is unchanged.
  2120. File: bison,  Node: Decl Summary,  Prev: Pure Decl,  Up: Declarations
  2121. Bison Declaration Summary
  2122. -------------------------
  2123.    Here is a summary of all Bison declarations:
  2124. `%union'
  2125.      Declare the collection of data types that semantic values may have
  2126.      (*note The Collection of Value Types: Union Decl.).
  2127. `%token'
  2128.      Declare a terminal symbol (token type name) with no precedence or
  2129.      associativity specified (*note Token Type Names: Token Decl.).
  2130. `%right'
  2131.      Declare a terminal symbol (token type name) that is
  2132.      right-associative (*note Operator Precedence: Precedence Decl.).
  2133. `%left'
  2134.      Declare a terminal symbol (token type name) that is
  2135.      left-associative (*note Operator Precedence: Precedence Decl.).
  2136. `%nonassoc'
  2137.      Declare a terminal symbol (token type name) that is nonassociative
  2138.      (using it in a way that would be associative is a syntax error)
  2139.      (*note Operator Precedence: Precedence Decl.).
  2140. `%type'
  2141.      Declare the type of semantic values for a nonterminal symbol
  2142.      (*note Nonterminal Symbols: Type Decl.).
  2143. `%start'
  2144.      Specify the grammar's start symbol (*note The Start-Symbol: Start
  2145.      Decl.).
  2146. `%expect'
  2147.      Declare the expected number of shift-reduce conflicts (*note
  2148.      Suppressing Conflict Warnings: Expect Decl.).
  2149. `%pure_parser'
  2150.      Request a pure (reentrant) parser program (*note A Pure
  2151.      (Reentrant) Parser: Pure Decl.).
  2152. File: bison,  Node: Multiple Parsers,  Prev: Declarations,  Up: Grammar File
  2153. Multiple Parsers in the Same Program
  2154. ====================================
  2155.    Most programs that use Bison parse only one language and therefore
  2156. contain only one Bison parser.  But what if you want to parse more than
  2157. one language with the same program?  Then you need to avoid a name
  2158. conflict between different definitions of `yyparse', `yylval', and so
  2159.    The easy way to do this is to use the option `-p PREFIX' (*note
  2160. Invoking Bison: Invocation.).  This renames the interface functions and
  2161. variables of the Bison parser to start with PREFIX instead of `yy'.
  2162. You can use this to give each parser distinct names that do not
  2163. conflict.
  2164.    The precise list of symbols renamed is `yyparse', `yylex',
  2165. `yyerror', `yylval', `yychar' and `yydebug'.  For example, if you use
  2166. `-p c', the names become `cparse', `clex', and so on.
  2167.    *All the other variables and macros associated with Bison are not
  2168. renamed.* These others are not global; there is no conflict if the same
  2169. name is used in different parsers.  For example, `YYSTYPE' is not
  2170. renamed, but defining this in different ways in different parsers causes
  2171. no trouble (*note Data Types of Semantic Values: Value Type.).
  2172.    The `-p' option works by adding macro definitions to the beginning
  2173. of the parser source file, defining `yyparse' as `PREFIXparse', and so
  2174. on.  This effectively substitutes one name for the other in the entire
  2175. parser file.
  2176. File: bison,  Node: Interface,  Next: Algorithm,  Prev: Grammar File,  Up: Top
  2177. Parser C-Language Interface
  2178. ***************************
  2179.    The Bison parser is actually a C function named `yyparse'.  Here we
  2180. describe the interface conventions of `yyparse' and the other functions
  2181. that it needs to use.
  2182.    Keep in mind that the parser uses many C identifiers starting with
  2183. `yy' and `YY' for internal purposes.  If you use such an identifier
  2184. (aside from those in this manual) in an action or in additional C code
  2185. in the grammar file, you are likely to run into trouble.
  2186. * Menu:
  2187. * Parser Function::   How to call `yyparse' and what it returns.
  2188. * Lexical::           You must supply a function `yylex'
  2189.                         which reads tokens.
  2190. * Error Reporting::   You must supply a function `yyerror'.
  2191. * Action Features::   Special features for use in actions.
  2192. File: bison,  Node: Parser Function,  Next: Lexical,  Up: Interface
  2193. The Parser Function `yyparse'
  2194. =============================
  2195.    You call the function `yyparse' to cause parsing to occur.  This
  2196. function reads tokens, executes actions, and ultimately returns when it
  2197. encounters end-of-input or an unrecoverable syntax error.  You can also
  2198. write an action which directs `yyparse' to return immediately without
  2199. reading further.
  2200.    The value returned by `yyparse' is 0 if parsing was successful
  2201. (return is due to end-of-input).
  2202.    The value is 1 if parsing failed (return is due to a syntax error).
  2203.    In an action, you can cause immediate return from `yyparse' by using
  2204. these macros:
  2205. `YYACCEPT'
  2206.      Return immediately with value 0 (to report success).
  2207. `YYABORT'
  2208.      Return immediately with value 1 (to report failure).
  2209. File: bison,  Node: Lexical,  Next: Error Reporting,  Prev: Parser Function,  Up: Interface
  2210. The Lexical Analyzer Function `yylex'
  2211. =====================================
  2212.    The "lexical analyzer" function, `yylex', recognizes tokens from the
  2213. input stream and returns them to the parser.  Bison does not create
  2214. this function automatically; you must write it so that `yyparse' can
  2215. call it.  The function is sometimes referred to as a lexical scanner.
  2216.    In simple programs, `yylex' is often defined at the end of the Bison
  2217. grammar file.  If `yylex' is defined in a separate source file, you
  2218. need to arrange for the token-type macro definitions to be available
  2219. there.  To do this, use the `-d' option when you run Bison, so that it
  2220. will write these macro definitions into a separate header file
  2221. `NAME.tab.h' which you can include in the other source files that need
  2222. it.  *Note Invoking Bison: Invocation.
  2223. * Menu:
  2224. * Calling Convention::  How `yyparse' calls `yylex'.
  2225. * Token Values::      How `yylex' must return the semantic value
  2226.                         of the token it has read.
  2227. * Token Positions::   How `yylex' must return the text position
  2228.                         (line number, etc.) of the token, if the
  2229.                         actions want that.
  2230. * Pure Calling::      How the calling convention differs
  2231.                         in a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.).
  2232. File: bison,  Node: Calling Convention,  Next: Token Values,  Up: Lexical
  2233. Calling Convention for `yylex'
  2234. ------------------------------
  2235.    The value that `yylex' returns must be the numeric code for the type
  2236. of token it has just found, or 0 for end-of-input.
  2237.    When a token is referred to in the grammar rules by a name, that name
  2238. in the parser file becomes a C macro whose definition is the proper
  2239. numeric code for that token type.  So `yylex' can use the name to
  2240. indicate that type.  *Note Symbols::.
  2241.    When a token is referred to in the grammar rules by a character
  2242. literal, the numeric code for that character is also the code for the
  2243. token type.  So `yylex' can simply return that character code.  The
  2244. null character must not be used this way, because its code is zero and
  2245. that is what signifies end-of-input.
  2246.    Here is an example showing these things:
  2247.      yylex ()
  2248.      {
  2249.        ...
  2250.        if (c == EOF)     /* Detect end of file. */
  2251.          return 0;
  2252.        ...
  2253.        if (c == '+' || c == '-')
  2254.          return c;      /* Assume token type for `+' is '+'. */
  2255.        ...
  2256.        return INT;      /* Return the type of the token. */
  2257.        ...
  2258.      }
  2259. This interface has been designed so that the output from the `lex'
  2260. utility can be used without change as the definition of `yylex'.
  2261. File: bison,  Node: Token Values,  Next: Token Positions,  Prev: Calling Convention,  Up: Lexical
  2262. Semantic Values of Tokens
  2263. -------------------------
  2264.    In an ordinary (nonreentrant) parser, the semantic value of the
  2265. token must be stored into the global variable `yylval'.  When you are
  2266. using just one data type for semantic values, `yylval' has that type.
  2267. Thus, if the type is `int' (the default), you might write this in
  2268. `yylex':
  2269.        ...
  2270.        yylval = value;  /* Put value onto Bison stack. */
  2271.        return INT;      /* Return the type of the token. */
  2272.        ...
  2273.    When you are using multiple data types, `yylval''s type is a union
  2274. made from the `%union' declaration (*note The Collection of Value
  2275. Types: Union Decl.).  So when you store a token's value, you must use
  2276. the proper member of the union.  If the `%union' declaration looks like
  2277. this:
  2278.      %union {
  2279.        int intval;
  2280.        double val;
  2281.        symrec *tptr;
  2282.      }
  2283. then the code in `yylex' might look like this:
  2284.        ...
  2285.        yylval.intval = value; /* Put value onto Bison stack. */
  2286.        return INT;          /* Return the type of the token. */
  2287.        ...
  2288. File: bison,  Node: Token Positions,  Next: Pure Calling,  Prev: Token Values,  Up: Lexical
  2289. Textual Positions of Tokens
  2290. ---------------------------
  2291.    If you are using the `@N'-feature (*note Special Features for Use in
  2292. Actions: Action Features.) in actions to keep track of the textual
  2293. locations of tokens and groupings, then you must provide this
  2294. information in `yylex'.  The function `yyparse' expects to find the
  2295. textual location of a token just parsed in the global variable
  2296. `yylloc'.  So `yylex' must store the proper data in that variable.  The
  2297. value of `yylloc' is a structure and you need only initialize the
  2298. members that are going to be used by the actions.  The four members are
  2299. called `first_line', `first_column', `last_line' and `last_column'.
  2300. Note that the use of this feature makes the parser noticeably slower.
  2301.    The data type of `yylloc' has the name `YYLTYPE'.
  2302. File: bison,  Node: Pure Calling,  Prev: Token Positions,  Up: Lexical
  2303. Calling for Pure Parsers
  2304. ------------------------
  2305.    When you use the Bison declaration `%pure_parser' to request a pure,
  2306. reentrant parser, the global communication variables `yylval' and
  2307. `yylloc' cannot be used.  (*Note A Pure (Reentrant) Parser: Pure Decl.)
  2308. In such parsers the two global variables are replaced by pointers
  2309. passed as arguments to `yylex'.  You must declare them as shown here,
  2310. and pass the information back by storing it through those pointers.
  2311.      yylex (lvalp, llocp)
  2312.           YYSTYPE *lvalp;
  2313.           YYLTYPE *llocp;
  2314.      {
  2315.        ...
  2316.        *lvalp = value;  /* Put value onto Bison stack.  */
  2317.        return INT;      /* Return the type of the token.  */
  2318.        ...
  2319.      }
  2320.    If the grammar file does not use the `@' constructs to refer to
  2321. textual positions, then the type `YYLTYPE' will not be defined.  In
  2322. this case, omit the second argument; `yylex' will be called with only
  2323. one argument.
  2324. File: bison,  Node: Error Reporting,  Next: Action Features,  Prev: Lexical,  Up: Interface
  2325. The Error Reporting Function `yyerror'
  2326. ======================================
  2327.    The Bison parser detects a "parse error" or "syntax error" whenever
  2328. it reads a token which cannot satisfy any syntax rule.  A action in the
  2329. grammar can also explicitly proclaim an error, using the macro
  2330. `YYERROR' (*note Special Features for Use in Actions: Action Features.).
  2331.    The Bison parser expects to report the error by calling an error
  2332. reporting function named `yyerror', which you must supply.  It is
  2333. called by `yyparse' whenever a syntax error is found, and it receives
  2334. one argument.  For a parse error, the string is normally
  2335. `"parse error"'.
  2336.    If you define the macro `YYERROR_VERBOSE' in the Bison declarations
  2337. section (*note The Bison Declarations Section: Bison Declarations.),
  2338. then Bison provides a more verbose and specific error message string
  2339. instead of just plain `"parse error"'.  It doesn't matter what
  2340. definition you use for `YYERROR_VERBOSE', just whether you define it.
  2341.    The parser can detect one other kind of error: stack overflow.  This
  2342. happens when the input contains constructions that are very deeply
  2343. nested.  It isn't likely you will encounter this, since the Bison
  2344. parser extends its stack automatically up to a very large limit.  But
  2345. if overflow happens, `yyparse' calls `yyerror' in the usual fashion,
  2346. except that the argument string is `"parser stack overflow"'.
  2347.    The following definition suffices in simple programs:
  2348.      yyerror (s)
  2349.           char *s;
  2350.      {
  2351.        fprintf (stderr, "%s\n", s);
  2352.      }
  2353.    After `yyerror' returns to `yyparse', the latter will attempt error
  2354. recovery if you have written suitable error recovery grammar rules
  2355. (*note Error Recovery::.).  If recovery is impossible, `yyparse' will
  2356. immediately return 1.
  2357.    The variable `yynerrs' contains the number of syntax errors
  2358. encountered so far.  Normally this variable is global; but if you
  2359. request a pure parser (*note A Pure (Reentrant) Parser: Pure Decl.)
  2360. then it is a local variable which only the actions can access.
  2361. File: bison,  Node: Action Features,  Prev: Error Reporting,  Up: Interface
  2362. Special Features for Use in Actions
  2363. ===================================
  2364.    Here is a table of Bison constructs, variables and macros that are
  2365. useful in actions.
  2366.      Acts like a variable that contains the semantic value for the
  2367.      grouping made by the current rule.  *Note Actions::.
  2368.      Acts like a variable that contains the semantic value for the Nth
  2369.      component of the current rule.  *Note Actions::.
  2370. `$<TYPEALT>$'
  2371.      Like `$$' but specifies alternative TYPEALT in the union specified
  2372.      by the `%union' declaration.  *Note Data Types of Values in
  2373.      Actions: Action Types.
  2374. `$<TYPEALT>N'
  2375.      Like `$N' but specifies alternative TYPEALT in the union specified
  2376.      by the `%union' declaration.  *Note Data Types of Values in
  2377.      Actions: Action Types.
  2378. `YYABORT;'
  2379.      Return immediately from `yyparse', indicating failure.  *Note The
  2380.      Parser Function `yyparse': Parser Function.
  2381. `YYACCEPT;'
  2382.      Return immediately from `yyparse', indicating success.  *Note The
  2383.      Parser Function `yyparse': Parser Function.
  2384. `YYBACKUP (TOKEN, VALUE);'
  2385.      Unshift a token.  This macro is allowed only for rules that reduce
  2386.      a single value, and only when there is no look-ahead token.  It
  2387.      installs a look-ahead token with token type TOKEN and semantic
  2388.      value VALUE; then it discards the value that was going to be
  2389.      reduced by this rule.
  2390.      If the macro is used when it is not valid, such as when there is a
  2391.      look-ahead token already, then it reports a syntax error with a
  2392.      message `cannot back up' and performs ordinary error recovery.
  2393.      In either case, the rest of the action is not executed.
  2394. `YYEMPTY'
  2395.      Value stored in `yychar' when there is no look-ahead token.
  2396. `YYERROR;'
  2397.      Cause an immediate syntax error.  This statement initiates error
  2398.      recovery just as if the parser itself had detected an error;
  2399.      however, it does not call `yyerror', and does not print any
  2400.      message.  If you want to print an error message, call `yyerror'
  2401.      explicitly before the `YYERROR;' statement.  *Note Error
  2402.      Recovery::.
  2403. `YYRECOVERING'
  2404.      This macro stands for an expression that has the value 1 when the
  2405.      parser is recovering from a syntax error, and 0 the rest of the
  2406.      time.  *Note Error Recovery::.
  2407. `yychar'
  2408.      Variable containing the current look-ahead token.  (In a pure
  2409.      parser, this is actually a local variable within `yyparse'.)  When
  2410.      there is no look-ahead token, the value `YYEMPTY' is stored in the
  2411.      variable.  *Note Look-Ahead Tokens: Look-Ahead.
  2412. `yyclearin;'
  2413.      Discard the current look-ahead token.  This is useful primarily in
  2414.      error rules.  *Note Error Recovery::.
  2415. `yyerrok;'
  2416.      Resume generating error messages immediately for subsequent syntax
  2417.      errors.  This is useful primarily in error rules.  *Note Error
  2418.      Recovery::.
  2419.      Acts like a structure variable containing information on the line
  2420.      numbers and column numbers of the Nth component of the current
  2421.      rule.  The structure has four members, like this:
  2422.           struct {
  2423.             int first_line, last_line;
  2424.             int first_column, last_column;
  2425.           };
  2426.      Thus, to get the starting line number of the third component, use
  2427.      `@3.first_line'.
  2428.      In order for the members of this structure to contain valid
  2429.      information, you must make `yylex' supply this information about
  2430.      each token.  If you need only certain members, then `yylex' need
  2431.      only fill in those members.
  2432.      The use of this feature makes the parser noticeably slower.
  2433. File: bison,  Node: Algorithm,  Next: Error Recovery,  Prev: Interface,  Up: Top
  2434. The Bison Parser Algorithm
  2435. **************************
  2436.    As Bison reads tokens, it pushes them onto a stack along with their
  2437. semantic values.  The stack is called the "parser stack".  Pushing a
  2438. token is traditionally called "shifting".
  2439.    For example, suppose the infix calculator has read `1 + 5 *', with a
  2440. `3' to come.  The stack will have four elements, one for each token
  2441. that was shifted.
  2442.    But the stack does not always have an element for each token read.
  2443. When the last N tokens and groupings shifted match the components of a
  2444. grammar rule, they can be combined according to that rule.  This is
  2445. called "reduction".  Those tokens and groupings are replaced on the
  2446. stack by a single grouping whose symbol is the result (left hand side)
  2447. of that rule.  Running the rule's action is part of the process of
  2448. reduction, because this is what computes the semantic value of the
  2449. resulting grouping.
  2450.    For example, if the infix calculator's parser stack contains this:
  2451.      1 + 5 * 3
  2452. and the next input token is a newline character, then the last three
  2453. elements can be reduced to 15 via the rule:
  2454.      expr: expr '*' expr;
  2455. Then the stack contains just these three elements:
  2456.      1 + 15
  2457. At this point, another reduction can be made, resulting in the single
  2458. value 16.  Then the newline token can be shifted.
  2459.    The parser tries, by shifts and reductions, to reduce the entire
  2460. input down to a single grouping whose symbol is the grammar's
  2461. start-symbol (*note Languages and Context-Free Grammars: Language and
  2462. Grammar.).
  2463.    This kind of parser is known in the literature as a bottom-up parser.
  2464. * Menu:
  2465. * Look-Ahead::        Parser looks one token ahead when deciding what to do.
  2466. * Shift/Reduce::      Conflicts: when either shifting or reduction is valid.
  2467. * Precedence::        Operator precedence works by resolving conflicts.
  2468. * Contextual Precedence::  When an operator's precedence depends on context.
  2469. * Parser States::     The parser is a finite-state-machine with stack.
  2470. * Reduce/Reduce::     When two rules are applicable in the same situation.
  2471. * Mystery Conflicts::  Reduce/reduce conflicts that look unjustified.
  2472. * Stack Overflow::    What happens when stack gets full.  How to avoid it.
  2473. File: bison,  Node: Look-Ahead,  Next: Shift/Reduce,  Up: Algorithm
  2474. Look-Ahead Tokens
  2475. =================
  2476.    The Bison parser does *not* always reduce immediately as soon as the
  2477. last N tokens and groupings match a rule.  This is because such a
  2478. simple strategy is inadequate to handle most languages.  Instead, when a
  2479. reduction is possible, the parser sometimes "looks ahead" at the next
  2480. token in order to decide what to do.
  2481.    When a token is read, it is not immediately shifted; first it
  2482. becomes the "look-ahead token", which is not on the stack.  Now the
  2483. parser can perform one or more reductions of tokens and groupings on
  2484. the stack, while the look-ahead token remains off to the side.  When no
  2485. more reductions should take place, the look-ahead token is shifted onto
  2486. the stack.  This does not mean that all possible reductions have been
  2487. done; depending on the token type of the look-ahead token, some rules
  2488. may choose to delay their application.
  2489.    Here is a simple case where look-ahead is needed.  These three rules
  2490. define expressions which contain binary addition operators and postfix
  2491. unary factorial operators (`!'), and allow parentheses for grouping.
  2492.      expr:     term '+' expr
  2493.              | term
  2494.              ;
  2495.      
  2496.      term:     '(' expr ')'
  2497.              | term '!'
  2498.              | NUMBER
  2499.              ;
  2500.    Suppose that the tokens `1 + 2' have been read and shifted; what
  2501. should be done?  If the following token is `)', then the first three
  2502. tokens must be reduced to form an `expr'.  This is the only valid
  2503. course, because shifting the `)' would produce a sequence of symbols
  2504. `term ')'', and no rule allows this.
  2505.    If the following token is `!', then it must be shifted immediately so
  2506. that `2 !' can be reduced to make a `term'.  If instead the parser were
  2507. to reduce before shifting, `1 + 2' would become an `expr'.  It would
  2508. then be impossible to shift the `!' because doing so would produce on
  2509. the stack the sequence of symbols `expr '!''.  No rule allows that
  2510. sequence.
  2511.    The current look-ahead token is stored in the variable `yychar'.
  2512. *Note Special Features for Use in Actions: Action Features.
  2513. File: bison,  Node: Shift/Reduce,  Next: Precedence,  Prev: Look-Ahead,  Up: Algorithm
  2514. Shift/Reduce Conflicts
  2515. ======================
  2516.    Suppose we are parsing a language which has if-then and if-then-else
  2517. statements, with a pair of rules like this:
  2518.      if_stmt:
  2519.                IF expr THEN stmt
  2520.              | IF expr THEN stmt ELSE stmt
  2521.              ;
  2522. Here we assume that `IF', `THEN' and `ELSE' are terminal symbols for
  2523. specific keyword tokens.
  2524.    When the `ELSE' token is read and becomes the look-ahead token, the
  2525. contents of the stack (assuming the input is valid) are just right for
  2526. reduction by the first rule.  But it is also legitimate to shift the
  2527. `ELSE', because that would lead to eventual reduction by the second
  2528. rule.
  2529.    This situation, where either a shift or a reduction would be valid,
  2530. is called a "shift/reduce conflict".  Bison is designed to resolve
  2531. these conflicts by choosing to shift, unless otherwise directed by
  2532. operator precedence declarations.  To see the reason for this, let's
  2533. contrast it with the other alternative.
  2534.    Since the parser prefers to shift the `ELSE', the result is to attach
  2535. the else-clause to the innermost if-statement, making these two inputs
  2536. equivalent:
  2537.      if x then if y then win (); else lose;
  2538.      
  2539.      if x then do; if y then win (); else lose; end;
  2540.    But if the parser chose to reduce when possible rather than shift,
  2541. the result would be to attach the else-clause to the outermost
  2542. if-statement, making these two inputs equivalent:
  2543.      if x then if y then win (); else lose;
  2544.      
  2545.      if x then do; if y then win (); end; else lose;
  2546.    The conflict exists because the grammar as written is ambiguous:
  2547. either parsing of the simple nested if-statement is legitimate.  The
  2548. established convention is that these ambiguities are resolved by
  2549. attaching the else-clause to the innermost if-statement; this is what
  2550. Bison accomplishes by choosing to shift rather than reduce.  (It would
  2551. ideally be cleaner to write an unambiguous grammar, but that is very
  2552. hard to do in this case.) This particular ambiguity was first
  2553. encountered in the specifications of Algol 60 and is called the
  2554. "dangling `else'" ambiguity.
  2555.    To avoid warnings from Bison about predictable, legitimate
  2556. shift/reduce conflicts, use the `%expect N' declaration.  There will be
  2557. no warning as long as the number of shift/reduce conflicts is exactly N.
  2558. *Note Suppressing Conflict Warnings: Expect Decl.
  2559.    The definition of `if_stmt' above is solely to blame for the
  2560. conflict, but the conflict does not actually appear without additional
  2561. rules.  Here is a complete Bison input file that actually manifests the
  2562. conflict:
  2563.      %token IF THEN ELSE variable
  2564.      %%
  2565.      stmt:     expr
  2566.              | if_stmt
  2567.              ;
  2568.      
  2569.      if_stmt:
  2570.                IF expr THEN stmt
  2571.              | IF expr THEN stmt ELSE stmt
  2572.              ;
  2573.      
  2574.      expr:     variable
  2575.              ;
  2576. File: bison,  Node: Precedence,  Next: Contextual Precedence,  Prev: Shift/Reduce,  Up: Algorithm
  2577. Operator Precedence
  2578. ===================
  2579.    Another situation where shift/reduce conflicts appear is in
  2580. arithmetic expressions.  Here shifting is not always the preferred
  2581. resolution; the Bison declarations for operator precedence allow you to
  2582. specify when to shift and when to reduce.
  2583. * Menu:
  2584. * Why Precedence::    An example showing why precedence is needed.
  2585. * Using Precedence::  How to specify precedence in Bison grammars.
  2586. * Precedence Examples::  How these features are used in the previous example.
  2587. * How Precedence::    How they work.
  2588. File: bison,  Node: Why Precedence,  Next: Using Precedence,  Up: Precedence
  2589. When Precedence is Needed
  2590. -------------------------
  2591.    Consider the following ambiguous grammar fragment (ambiguous because
  2592. the input `1 - 2 * 3' can be parsed in two different ways):
  2593.      expr:     expr '-' expr
  2594.              | expr '*' expr
  2595.              | expr '<' expr
  2596.              | '(' expr ')'
  2597.              ...
  2598.              ;
  2599. Suppose the parser has seen the tokens `1', `-' and `2'; should it
  2600. reduce them via the rule for the addition operator?  It depends on the
  2601. next token.  Of course, if the next token is `)', we must reduce;
  2602. shifting is invalid because no single rule can reduce the token
  2603. sequence `- 2 )' or anything starting with that.  But if the next token
  2604. is `*' or `<', we have a choice: either shifting or reduction would
  2605. allow the parse to complete, but with different results.
  2606.    To decide which one Bison should do, we must consider the results.
  2607. If the next operator token OP is shifted, then it must be reduced first
  2608. in order to permit another opportunity to reduce the sum.  The result
  2609. is (in effect) `1 - (2 OP 3)'.  On the other hand, if the subtraction
  2610. is reduced before shifting OP, the result is `(1 - 2) OP 3'.  Clearly,
  2611. then, the choice of shift or reduce should depend on the relative
  2612. precedence of the operators `-' and OP: `*' should be shifted first,
  2613. but not `<'.
  2614.    What about input such as `1 - 2 - 5'; should this be `(1 - 2) - 5'
  2615. or should it be `1 - (2 - 5)'?  For most operators we prefer the
  2616. former, which is called "left association".  The latter alternative,
  2617. "right association", is desirable for assignment operators.  The choice
  2618. of left or right association is a matter of whether the parser chooses
  2619. to shift or reduce when the stack contains `1 - 2' and the look-ahead
  2620. token is `-': shifting makes right-associativity.
  2621. File: bison,  Node: Using Precedence,  Next: Precedence Examples,  Prev: Why Precedence,  Up: Precedence
  2622. Specifying Operator Precedence
  2623. ------------------------------
  2624.    Bison allows you to specify these choices with the operator
  2625. precedence declarations `%left' and `%right'.  Each such declaration
  2626. contains a list of tokens, which are operators whose precedence and
  2627. associativity is being declared.  The `%left' declaration makes all
  2628. those operators left-associative and the `%right' declaration makes
  2629. them right-associative.  A third alternative is `%nonassoc', which
  2630. declares that it is a syntax error to find the same operator twice "in a
  2631. row".
  2632.    The relative precedence of different operators is controlled by the
  2633. order in which they are declared.  The first `%left' or `%right'
  2634. declaration in the file declares the operators whose precedence is
  2635. lowest, the next such declaration declares the operators whose
  2636. precedence is a little higher, and so on.
  2637. File: bison,  Node: Precedence Examples,  Next: How Precedence,  Prev: Using Precedence,  Up: Precedence
  2638. Precedence Examples
  2639. -------------------
  2640.    In our example, we would want the following declarations:
  2641.      %left '<'
  2642.      %left '-'
  2643.      %left '*'
  2644.    In a more complete example, which supports other operators as well,
  2645. we would declare them in groups of equal precedence.  For example,
  2646. `'+'' is declared with `'-'':
  2647.      %left '<' '>' '=' NE LE GE
  2648.      %left '+' '-'
  2649.      %left '*' '/'
  2650. (Here `NE' and so on stand for the operators for "not equal" and so on.
  2651. We assume that these tokens are more than one character long and
  2652. therefore are represented by names, not character literals.)
  2653. File: bison,  Node: How Precedence,  Prev: Precedence Examples,  Up: Precedence
  2654. How Precedence Works
  2655. --------------------
  2656.    The first effect of the precedence declarations is to assign
  2657. precedence levels to the terminal symbols declared.  The second effect
  2658. is to assign precedence levels to certain rules: each rule gets its
  2659. precedence from the last terminal symbol mentioned in the components.
  2660. (You can also specify explicitly the precedence of a rule.  *Note
  2661. Context-Dependent Precedence: Contextual Precedence.)
  2662.    Finally, the resolution of conflicts works by comparing the
  2663. precedence of the rule being considered with that of the look-ahead
  2664. token.  If the token's precedence is higher, the choice is to shift.
  2665. If the rule's precedence is higher, the choice is to reduce.  If they
  2666. have equal precedence, the choice is made based on the associativity of
  2667. that precedence level.  The verbose output file made by `-v' (*note
  2668. Invoking Bison: Invocation.) says how each conflict was resolved.
  2669.    Not all rules and not all tokens have precedence.  If either the
  2670. rule or the look-ahead token has no precedence, then the default is to
  2671. shift.
  2672. File: bison,  Node: Contextual Precedence,  Next: Parser States,  Prev: Precedence,  Up: Algorithm
  2673. Context-Dependent Precedence
  2674. ============================
  2675.    Often the precedence of an operator depends on the context.  This
  2676. sounds outlandish at first, but it is really very common.  For example,
  2677. a minus sign typically has a very high precedence as a unary operator,
  2678. and a somewhat lower precedence (lower than multiplication) as a binary
  2679. operator.
  2680.    The Bison precedence declarations, `%left', `%right' and
  2681. `%nonassoc', can only be used once for a given token; so a token has
  2682. only one precedence declared in this way.  For context-dependent
  2683. precedence, you need to use an additional mechanism: the `%prec'
  2684. modifier for rules.
  2685.    The `%prec' modifier declares the precedence of a particular rule by
  2686. specifying a terminal symbol whose precedence should be used for that
  2687. rule.  It's not necessary for that symbol to appear otherwise in the
  2688. rule.  The modifier's syntax is:
  2689.      %prec TERMINAL-SYMBOL
  2690. and it is written after the components of the rule.  Its effect is to
  2691. assign the rule the precedence of TERMINAL-SYMBOL, overriding the
  2692. precedence that would be deduced for it in the ordinary way.  The
  2693. altered rule precedence then affects how conflicts involving that rule
  2694. are resolved (*note Operator Precedence: Precedence.).
  2695.    Here is how `%prec' solves the problem of unary minus.  First,
  2696. declare a precedence for a fictitious terminal symbol named `UMINUS'.
  2697. There are no tokens of this type, but the symbol serves to stand for its
  2698. precedence:
  2699.      ...
  2700.      %left '+' '-'
  2701.      %left '*'
  2702.      %left UMINUS
  2703.    Now the precedence of `UMINUS' can be used in specific rules:
  2704.      exp:    ...
  2705.              | exp '-' exp
  2706.              ...
  2707.              | '-' exp %prec UMINUS
  2708. File: bison,  Node: Parser States,  Next: Reduce/Reduce,  Prev: Contextual Precedence,  Up: Algorithm
  2709. Parser States
  2710. =============
  2711.    The function `yyparse' is implemented using a finite-state machine.
  2712. The values pushed on the parser stack are not simply token type codes;
  2713. they represent the entire sequence of terminal and nonterminal symbols
  2714. at or near the top of the stack.  The current state collects all the
  2715. information about previous input which is relevant to deciding what to
  2716. do next.
  2717.    Each time a look-ahead token is read, the current parser state
  2718. together with the type of look-ahead token are looked up in a table.
  2719. This table entry can say, "Shift the look-ahead token."  In this case,
  2720. it also specifies the new parser state, which is pushed onto the top of
  2721. the parser stack.  Or it can say, "Reduce using rule number N." This
  2722. means that a certain number of tokens or groupings are taken off the
  2723. top of the stack, and replaced by one grouping.  In other words, that
  2724. number of states are popped from the stack, and one new state is pushed.
  2725.    There is one other alternative: the table can say that the
  2726. look-ahead token is erroneous in the current state.  This causes error
  2727. processing to begin (*note Error Recovery::.).
  2728. File: bison,  Node: Reduce/Reduce,  Next: Mystery Conflicts,  Prev: Parser States,  Up: Algorithm
  2729. Reduce/Reduce Conflicts
  2730. =======================
  2731.    A reduce/reduce conflict occurs if there are two or more rules that
  2732. apply to the same sequence of input.  This usually indicates a serious
  2733. error in the grammar.
  2734.    For example, here is an erroneous attempt to define a sequence of
  2735. zero or more `word' groupings.
  2736.      sequence: /* empty */
  2737.                      { printf ("empty sequence\n"); }
  2738.              | maybeword
  2739.              | sequence word
  2740.                      { printf ("added word %s\n", $2); }
  2741.              ;
  2742.      
  2743.      maybeword: /* empty */
  2744.                      { printf ("empty maybeword\n"); }
  2745.              | word
  2746.                      { printf ("single word %s\n", $1); }
  2747.              ;
  2748. The error is an ambiguity: there is more than one way to parse a single
  2749. `word' into a `sequence'.  It could be reduced to a `maybeword' and
  2750. then into a `sequence' via the second rule.  Alternatively,
  2751. nothing-at-all could be reduced into a `sequence' via the first rule,
  2752. and this could be combined with the `word' using the third rule for
  2753. `sequence'.
  2754.    There is also more than one way to reduce nothing-at-all into a
  2755. `sequence'.  This can be done directly via the first rule, or
  2756. indirectly via `maybeword' and then the second rule.
  2757.    You might think that this is a distinction without a difference,
  2758. because it does not change whether any particular input is valid or
  2759. not.  But it does affect which actions are run.  One parsing order runs
  2760. the second rule's action; the other runs the first rule's action and
  2761. the third rule's action.  In this example, the output of the program
  2762. changes.
  2763.    Bison resolves a reduce/reduce conflict by choosing to use the rule
  2764. that appears first in the grammar, but it is very risky to rely on
  2765. this.  Every reduce/reduce conflict must be studied and usually
  2766. eliminated.  Here is the proper way to define `sequence':
  2767.      sequence: /* empty */
  2768.                      { printf ("empty sequence\n"); }
  2769.              | sequence word
  2770.                      { printf ("added word %s\n", $2); }
  2771.              ;
  2772.    Here is another common error that yields a reduce/reduce conflict:
  2773.      sequence: /* empty */
  2774.              | sequence words
  2775.              | sequence redirects
  2776.              ;
  2777.      
  2778.      words:    /* empty */
  2779.              | words word
  2780.              ;
  2781.      
  2782.      redirects:/* empty */
  2783.              | redirects redirect
  2784.              ;
  2785. The intention here is to define a sequence which can contain either
  2786. `word' or `redirect' groupings.  The individual definitions of
  2787. `sequence', `words' and `redirects' are error-free, but the three
  2788. together make a subtle ambiguity: even an empty input can be parsed in
  2789. infinitely many ways!
  2790.    Consider: nothing-at-all could be a `words'.  Or it could be two
  2791. `words' in a row, or three, or any number.  It could equally well be a
  2792. `redirects', or two, or any number.  Or it could be a `words' followed
  2793. by three `redirects' and another `words'.  And so on.
  2794.    Here are two ways to correct these rules.  First, to make it a
  2795. single level of sequence:
  2796.      sequence: /* empty */
  2797.              | sequence word
  2798.              | sequence redirect
  2799.              ;
  2800.    Second, to prevent either a `words' or a `redirects' from being
  2801. empty:
  2802.      sequence: /* empty */
  2803.              | sequence words
  2804.              | sequence redirects
  2805.              ;
  2806.      
  2807.      words:    word
  2808.              | words word
  2809.              ;
  2810.      
  2811.      redirects:redirect
  2812.              | redirects redirect
  2813.              ;
  2814. File: bison,  Node: Mystery Conflicts,  Next: Stack Overflow,  Prev: Reduce/Reduce,  Up: Algorithm
  2815. Mysterious Reduce/Reduce Conflicts
  2816. ==================================
  2817.    Sometimes reduce/reduce conflicts can occur that don't look
  2818. warranted.  Here is an example:
  2819.      %token ID
  2820.      
  2821.      %%
  2822.      def:    param_spec return_spec ','
  2823.              ;
  2824.      param_spec:
  2825.                   type
  2826.              |    name_list ':' type
  2827.              ;
  2828.      return_spec:
  2829.                   type
  2830.              |    name ':' type
  2831.              ;
  2832.      type:        ID
  2833.              ;
  2834.      name:        ID
  2835.              ;
  2836.      name_list:
  2837.                   name
  2838.              |    name ',' name_list
  2839.              ;
  2840.    It would seem that this grammar can be parsed with only a single
  2841. token of look-ahead: when a `param_spec' is being read, an `ID' is a
  2842. `name' if a comma or colon follows, or a `type' if another `ID'
  2843. follows.  In other words, this grammar is LR(1).
  2844.    However, Bison, like most parser generators, cannot actually handle
  2845. all LR(1) grammars.  In this grammar, two contexts, that after an `ID'
  2846. at the beginning of a `param_spec' and likewise at the beginning of a
  2847. `return_spec', are similar enough that Bison assumes they are the same.
  2848. They appear similar because the same set of rules would be active--the
  2849. rule for reducing to a `name' and that for reducing to a `type'.  Bison
  2850. is unable to determine at that stage of processing that the rules would
  2851. require different look-ahead tokens in the two contexts, so it makes a
  2852. single parser state for them both.  Combining the two contexts causes a
  2853. conflict later.  In parser terminology, this occurrence means that the
  2854. grammar is not LALR(1).
  2855.    In general, it is better to fix deficiencies than to document them.
  2856. But this particular deficiency is intrinsically hard to fix; parser
  2857. generators that can handle LR(1) grammars are hard to write and tend to
  2858. produce parsers that are very large.  In practice, Bison is more useful
  2859. as it is now.
  2860.    When the problem arises, you can often fix it by identifying the two
  2861. parser states that are being confused, and adding something to make them
  2862. look distinct.  In the above example, adding one rule to `return_spec'
  2863. as follows makes the problem go away:
  2864.      %token BOGUS
  2865.      ...
  2866.      %%
  2867.      ...
  2868.      return_spec:
  2869.                   type
  2870.              |    name ':' type
  2871.              /* This rule is never used.  */
  2872.              |    ID BOGUS
  2873.              ;
  2874.    This corrects the problem because it introduces the possibility of an
  2875. additional active rule in the context after the `ID' at the beginning of
  2876. `return_spec'.  This rule is not active in the corresponding context in
  2877. a `param_spec', so the two contexts receive distinct parser states.  As
  2878. long as the token `BOGUS' is never generated by `yylex', the added rule
  2879. cannot alter the way actual input is parsed.
  2880.    In this particular example, there is another way to solve the
  2881. problem: rewrite the rule for `return_spec' to use `ID' directly
  2882. instead of via `name'.  This also causes the two confusing contexts to
  2883. have different sets of active rules, because the one for `return_spec'
  2884. activates the altered rule for `return_spec' rather than the one for
  2885. `name'.
  2886.      param_spec:
  2887.                   type
  2888.              |    name_list ':' type
  2889.              ;
  2890.      return_spec:
  2891.                   type
  2892.              |    ID ':' type
  2893.              ;
  2894. File: bison,  Node: Stack Overflow,  Prev: Mystery Conflicts,  Up: Algorithm
  2895. Stack Overflow, and How to Avoid It
  2896. ===================================
  2897.    The Bison parser stack can overflow if too many tokens are shifted
  2898. and not reduced.  When this happens, the parser function `yyparse'
  2899. returns a nonzero value, pausing only to call `yyerror' to report the
  2900. overflow.
  2901.    By defining the macro `YYMAXDEPTH', you can control how deep the
  2902. parser stack can become before a stack overflow occurs.  Define the
  2903. macro with a value that is an integer.  This value is the maximum number
  2904. of tokens that can be shifted (and not reduced) before overflow.  It
  2905. must be a constant expression whose value is known at compile time.
  2906.    The stack space allowed is not necessarily allocated.  If you
  2907. specify a large value for `YYMAXDEPTH', the parser actually allocates a
  2908. small stack at first, and then makes it bigger by stages as needed.
  2909. This increasing allocation happens automatically and silently.
  2910. Therefore, you do not need to make `YYMAXDEPTH' painfully small merely
  2911. to save space for ordinary inputs that do not need much stack.
  2912.    The default value of `YYMAXDEPTH', if you do not define it, is 10000.
  2913.    You can control how much stack is allocated initially by defining the
  2914. macro `YYINITDEPTH'.  This value too must be a compile-time constant
  2915. integer.  The default is 200.
  2916. File: bison,  Node: Error Recovery,  Next: Context Dependency,  Prev: Algorithm,  Up: Top
  2917. Error Recovery
  2918. **************
  2919.    It is not usually acceptable to have a program terminate on a parse
  2920. error.  For example, a compiler should recover sufficiently to parse the
  2921. rest of the input file and check it for errors; a calculator should
  2922. accept another expression.
  2923.    In a simple interactive command parser where each input is one line,
  2924. it may be sufficient to allow `yyparse' to return 1 on error and have
  2925. the caller ignore the rest of the input line when that happens (and
  2926. then call `yyparse' again).  But this is inadequate for a compiler,
  2927. because it forgets all the syntactic context leading up to the error.
  2928. A syntax error deep within a function in the compiler input should not
  2929. cause the compiler to treat the following line like the beginning of a
  2930. source file.
  2931.    You can define how to recover from a syntax error by writing rules to
  2932. recognize the special token `error'.  This is a terminal symbol that is
  2933. always defined (you need not declare it) and reserved for error
  2934. handling.  The Bison parser generates an `error' token whenever a
  2935. syntax error happens; if you have provided a rule to recognize this
  2936. token in the current context, the parse can continue.
  2937.    For example:
  2938.      stmnts:  /* empty string */
  2939.              | stmnts '\n'
  2940.              | stmnts exp '\n'
  2941.              | stmnts error '\n'
  2942.    The fourth rule in this example says that an error followed by a
  2943. newline makes a valid addition to any `stmnts'.
  2944.    What happens if a syntax error occurs in the middle of an `exp'?  The
  2945. error recovery rule, interpreted strictly, applies to the precise
  2946. sequence of a `stmnts', an `error' and a newline.  If an error occurs in
  2947. the middle of an `exp', there will probably be some additional tokens
  2948. and subexpressions on the stack after the last `stmnts', and there will
  2949. be tokens to read before the next newline.  So the rule is not
  2950. applicable in the ordinary way.
  2951.    But Bison can force the situation to fit the rule, by discarding
  2952. part of the semantic context and part of the input.  First it discards
  2953. states and objects from the stack until it gets back to a state in
  2954. which the `error' token is acceptable.  (This means that the
  2955. subexpressions already parsed are discarded, back to the last complete
  2956. `stmnts'.)  At this point the `error' token can be shifted.  Then, if
  2957. the old look-ahead token is not acceptable to be shifted next, the
  2958. parser reads tokens and discards them until it finds a token which is
  2959. acceptable.  In this example, Bison reads and discards input until the
  2960. next newline so that the fourth rule can apply.
  2961.    The choice of error rules in the grammar is a choice of strategies
  2962. for error recovery.  A simple and useful strategy is simply to skip the
  2963. rest of the current input line or current statement if an error is
  2964. detected:
  2965.      stmnt: error ';'  /* on error, skip until ';' is read */
  2966.    It is also useful to recover to the matching close-delimiter of an
  2967. opening-delimiter that has already been parsed.  Otherwise the
  2968. close-delimiter will probably appear to be unmatched, and generate
  2969. another, spurious error message:
  2970.      primary:  '(' expr ')'
  2971.              | '(' error ')'
  2972.              ...
  2973.              ;
  2974.    Error recovery strategies are necessarily guesses.  When they guess
  2975. wrong, one syntax error often leads to another.  In the above example,
  2976. the error recovery rule guesses that an error is due to bad input
  2977. within one `stmnt'.  Suppose that instead a spurious semicolon is
  2978. inserted in the middle of a valid `stmnt'.  After the error recovery
  2979. rule recovers from the first error, another syntax error will be found
  2980. straightaway, since the text following the spurious semicolon is also
  2981. an invalid `stmnt'.
  2982.    To prevent an outpouring of error messages, the parser will output
  2983. no error message for another syntax error that happens shortly after
  2984. the first; only after three consecutive input tokens have been
  2985. successfully shifted will error messages resume.
  2986.    Note that rules which accept the `error' token may have actions, just
  2987. as any other rules can.
  2988.    You can make error messages resume immediately by using the macro
  2989. `yyerrok' in an action.  If you do this in the error rule's action, no
  2990. error messages will be suppressed.  This macro requires no arguments;
  2991. `yyerrok;' is a valid C statement.
  2992.    The previous look-ahead token is reanalyzed immediately after an
  2993. error.  If this is unacceptable, then the macro `yyclearin' may be used
  2994. to clear this token.  Write the statement `yyclearin;' in the error
  2995. rule's action.
  2996.    For example, suppose that on a parse error, an error handling
  2997. routine is called that advances the input stream to some point where
  2998. parsing should once again commence.  The next symbol returned by the
  2999. lexical scanner is probably correct.  The previous look-ahead token
  3000. ought to be discarded with `yyclearin;'.
  3001.    The macro `YYRECOVERING' stands for an expression that has the value
  3002. 1 when the parser is recovering from a syntax error, and 0 the rest of
  3003. the time.  A value of 1 indicates that error messages are currently
  3004. suppressed for new syntax errors.
  3005. File: bison,  Node: Context Dependency,  Next: Debugging,  Prev: Error Recovery,  Up: Top
  3006. Handling Context Dependencies
  3007. *****************************
  3008.    The Bison paradigm is to parse tokens first, then group them into
  3009. larger syntactic units.  In many languages, the meaning of a token is
  3010. affected by its context.  Although this violates the Bison paradigm,
  3011. certain techniques (known as "kludges") may enable you to write Bison
  3012. parsers for such languages.
  3013. * Menu:
  3014. * Semantic Tokens::   Token parsing can depend on the semantic context.
  3015. * Lexical Tie-ins::   Token parsing can depend on the syntactic context.
  3016. * Tie-in Recovery::   Lexical tie-ins have implications for how
  3017.                         error recovery rules must be written.
  3018.    (Actually, "kludge" means any technique that gets its job done but is
  3019. neither clean nor robust.)
  3020. File: bison,  Node: Semantic Tokens,  Next: Lexical Tie-ins,  Up: Context Dependency
  3021. Semantic Info in Token Types
  3022. ============================
  3023.    The C language has a context dependency: the way an identifier is
  3024. used depends on what its current meaning is.  For example, consider
  3025. this:
  3026.      foo (x);
  3027.    This looks like a function call statement, but if `foo' is a typedef
  3028. name, then this is actually a declaration of `x'.  How can a Bison
  3029. parser for C decide how to parse this input?
  3030.    The method used in GNU C is to have two different token types,
  3031. `IDENTIFIER' and `TYPENAME'.  When `yylex' finds an identifier, it
  3032. looks up the current declaration of the identifier in order to decide
  3033. which token type to return: `TYPENAME' if the identifier is declared as
  3034. a typedef, `IDENTIFIER' otherwise.
  3035.    The grammar rules can then express the context dependency by the
  3036. choice of token type to recognize.  `IDENTIFIER' is accepted as an
  3037. expression, but `TYPENAME' is not.  `TYPENAME' can start a declaration,
  3038. but `IDENTIFIER' cannot.  In contexts where the meaning of the
  3039. identifier is *not* significant, such as in declarations that can
  3040. shadow a typedef name, either `TYPENAME' or `IDENTIFIER' is
  3041. accepted--there is one rule for each of the two token types.
  3042.    This technique is simple to use if the decision of which kinds of
  3043. identifiers to allow is made at a place close to where the identifier is
  3044. parsed.  But in C this is not always so: C allows a declaration to
  3045. redeclare a typedef name provided an explicit type has been specified
  3046. earlier:
  3047.      typedef int foo, bar, lose;
  3048.      static foo (bar);        /* redeclare `bar' as static variable */
  3049.      static int foo (lose);   /* redeclare `foo' as function */
  3050.    Unfortunately, the name being declared is separated from the
  3051. declaration construct itself by a complicated syntactic structure--the
  3052. "declarator".
  3053.    As a result, the part of Bison parser for C needs to be duplicated,
  3054. with all the nonterminal names changed: once for parsing a declaration
  3055. in which a typedef name can be redefined, and once for parsing a
  3056. declaration in which that can't be done.  Here is a part of the
  3057. duplication, with actions omitted for brevity:
  3058.      initdcl:
  3059.                declarator maybeasm '='
  3060.                init
  3061.              | declarator maybeasm
  3062.              ;
  3063.      
  3064.      notype_initdcl:
  3065.                notype_declarator maybeasm '='
  3066.                init
  3067.              | notype_declarator maybeasm
  3068.              ;
  3069. Here `initdcl' can redeclare a typedef name, but `notype_initdcl'
  3070. cannot.  The distinction between `declarator' and `notype_declarator'
  3071. is the same sort of thing.
  3072.    There is some similarity between this technique and a lexical tie-in
  3073. (described next), in that information which alters the lexical analysis
  3074. is changed during parsing by other parts of the program.  The
  3075. difference is here the information is global, and is used for other
  3076. purposes in the program.  A true lexical tie-in has a special-purpose
  3077. flag controlled by the syntactic context.
  3078. File: bison,  Node: Lexical Tie-ins,  Next: Tie-in Recovery,  Prev: Semantic Tokens,  Up: Context Dependency
  3079. Lexical Tie-ins
  3080. ===============
  3081.    One way to handle context-dependency is the "lexical tie-in": a flag
  3082. which is set by Bison actions, whose purpose is to alter the way tokens
  3083. are parsed.
  3084.    For example, suppose we have a language vaguely like C, but with a
  3085. special construct `hex (HEX-EXPR)'.  After the keyword `hex' comes an
  3086. expression in parentheses in which all integers are hexadecimal.  In
  3087. particular, the token `a1b' must be treated as an integer rather than
  3088. as an identifier if it appears in that context.  Here is how you can do
  3089.      %{
  3090.      int hexflag;
  3091.      %}
  3092.      %%
  3093.      ...
  3094.      expr:   IDENTIFIER
  3095.              | constant
  3096.              | HEX '('
  3097.                      { hexflag = 1; }
  3098.                expr ')'
  3099.                      { hexflag = 0;
  3100.                         $$ = $4; }
  3101.              | expr '+' expr
  3102.                      { $$ = make_sum ($1, $3); }
  3103.              ...
  3104.              ;
  3105.      
  3106.      constant:
  3107.                INTEGER
  3108.              | STRING
  3109.              ;
  3110. Here we assume that `yylex' looks at the value of `hexflag'; when it is
  3111. nonzero, all integers are parsed in hexadecimal, and tokens starting
  3112. with letters are parsed as integers if possible.
  3113.    The declaration of `hexflag' shown in the C declarations section of
  3114. the parser file is needed to make it accessible to the actions (*note
  3115. The C Declarations Section: C Declarations.).  You must also write the
  3116. code in `yylex' to obey the flag.
  3117. File: bison,  Node: Tie-in Recovery,  Prev: Lexical Tie-ins,  Up: Context Dependency
  3118. Lexical Tie-ins and Error Recovery
  3119. ==================================
  3120.    Lexical tie-ins make strict demands on any error recovery rules you
  3121. have.  *Note Error Recovery::.
  3122.    The reason for this is that the purpose of an error recovery rule is
  3123. to abort the parsing of one construct and resume in some larger
  3124. construct.  For example, in C-like languages, a typical error recovery
  3125. rule is to skip tokens until the next semicolon, and then start a new
  3126. statement, like this:
  3127.      stmt:   expr ';'
  3128.              | IF '(' expr ')' stmt { ... }
  3129.              ...
  3130.              error ';'
  3131.                      { hexflag = 0; }
  3132.              ;
  3133.    If there is a syntax error in the middle of a `hex (EXPR)'
  3134. construct, this error rule will apply, and then the action for the
  3135. completed `hex (EXPR)' will never run.  So `hexflag' would remain set
  3136. for the entire rest of the input, or until the next `hex' keyword,
  3137. causing identifiers to be misinterpreted as integers.
  3138.    To avoid this problem the error recovery rule itself clears
  3139. `hexflag'.
  3140.    There may also be an error recovery rule that works within
  3141. expressions.  For example, there could be a rule which applies within
  3142. parentheses and skips to the close-parenthesis:
  3143.      expr:   ...
  3144.              | '(' expr ')'
  3145.                      { $$ = $2; }
  3146.              | '(' error ')'
  3147.              ...
  3148.    If this rule acts within the `hex' construct, it is not going to
  3149. abort that construct (since it applies to an inner level of parentheses
  3150. within the construct).  Therefore, it should not clear the flag: the
  3151. rest of the `hex' construct should be parsed with the flag still in
  3152. effect.
  3153.    What if there is an error recovery rule which might abort out of the
  3154. `hex' construct or might not, depending on circumstances?  There is no
  3155. way you can write the action to determine whether a `hex' construct is
  3156. being aborted or not.  So if you are using a lexical tie-in, you had
  3157. better make sure your error recovery rules are not of this kind.  Each
  3158. rule must be such that you can be sure that it always will, or always
  3159. won't, have to clear the flag.
  3160. File: bison,  Node: Debugging,  Next: Invocation,  Prev: Context Dependency,  Up: Top
  3161. Debugging Your Parser
  3162. *********************
  3163.    If a Bison grammar compiles properly but doesn't do what you want
  3164. when it runs, the `yydebug' parser-trace feature can help you figure
  3165. out why.
  3166.    To enable compilation of trace facilities, you must define the macro
  3167. `YYDEBUG' when you compile the parser.  You could use `-DYYDEBUG=1' as
  3168. a compiler option or you could put `#define YYDEBUG 1' in the C
  3169. declarations section of the grammar file (*note The C Declarations
  3170. Section: C Declarations.).  Alternatively, use the `-t' option when you
  3171. run Bison (*note Invoking Bison: Invocation.).  We always define
  3172. `YYDEBUG' so that debugging is always possible.
  3173.    The trace facility uses `stderr', so you must add
  3174. `#include <stdio.h>' to the C declarations section unless it is already
  3175. there.
  3176.    Once you have compiled the program with trace facilities, the way to
  3177. request a trace is to store a nonzero value in the variable `yydebug'.
  3178. You can do this by making the C code do it (in `main', perhaps), or you
  3179. can alter the value with a C debugger.
  3180.    Each step taken by the parser when `yydebug' is nonzero produces a
  3181. line or two of trace information, written on `stderr'.  The trace
  3182. messages tell you these things:
  3183.    * Each time the parser calls `yylex', what kind of token was read.
  3184.    * Each time a token is shifted, the depth and complete contents of
  3185.      the state stack (*note Parser States::.).
  3186.    * Each time a rule is reduced, which rule it is, and the complete
  3187.      contents of the state stack afterward.
  3188.    To make sense of this information, it helps to refer to the listing
  3189. file produced by the Bison `-v' option (*note Invoking Bison:
  3190. Invocation.).  This file shows the meaning of each state in terms of
  3191. positions in various rules, and also what each state will do with each
  3192. possible input token.  As you read the successive trace messages, you
  3193. can see that the parser is functioning according to its specification
  3194. in the listing file.  Eventually you will arrive at the place where
  3195. something undesirable happens, and you will see which parts of the
  3196. grammar are to blame.
  3197.    The parser file is a C program and you can use C debuggers on it,
  3198. but it's not easy to interpret what it is doing.  The parser function
  3199. is a finite-state machine interpreter, and aside from the actions it
  3200. executes the same code over and over.  Only the values of variables
  3201. show where in the grammar it is working.
  3202.    The debugging information normally gives the token type of each token
  3203. read, but not its semantic value.  You can optionally define a macro
  3204. named `YYPRINT' to provide a way to print the value.  If you define
  3205. `YYPRINT', it should take three arguments.  The parser will pass a
  3206. standard I/O stream, the numeric code for the token type, and the token
  3207. value (from `yylval').
  3208.    Here is an example of `YYPRINT' suitable for the multi-function
  3209. calculator (*note Declarations for `mfcalc': Mfcalc Decl.):
  3210.      #define YYPRINT(file, type, value)   yyprint (file, type, value)
  3211.      
  3212.      static void
  3213.      yyprint (file, type, value)
  3214.           FILE *file;
  3215.           int type;
  3216.           YYSTYPE value;
  3217.      {
  3218.        if (type == VAR)
  3219.          fprintf (file, " %s", value.tptr->name);
  3220.        else if (type == NUM)
  3221.          fprintf (file, " %d", value.val);
  3222.      }
  3223. File: bison,  Node: Invocation,  Next: Table of Symbols,  Prev: Debugging,  Up: Top
  3224. Invoking Bison
  3225. **************
  3226.    The usual way to invoke Bison is as follows:
  3227.      bison INFILE
  3228.    Here INFILE is the grammar file name, which usually ends in `.y'.
  3229. The parser file's name is made by replacing the `.y' with `.tab.c'.
  3230. Thus, the `bison foo.y' filename yields `foo.tab.c', and the `bison
  3231. hack/foo.y' filename yields `hack/foo.tab.c'.
  3232. * Menu:
  3233. * Bison Options::     All the options described in detail,
  3234.             in alphabetical order by short options.
  3235. * Option Cross Key::  Alphabetical list of long options.
  3236. * VMS Invocation::    Bison command syntax on VMS.
  3237. File: bison,  Node: Bison Options,  Next: Option Cross Key,  Up: Invocation
  3238. Bison Options
  3239. =============
  3240.    Bison supports both traditional single-letter options and mnemonic
  3241. long option names.  Long option names are indicated with `--' instead of
  3242. `-'.  Abbreviations for option names are allowed as long as they are
  3243. unique.  When a long option takes an argument, like `--file-prefix',
  3244. connect the option name and the argument with `='.
  3245.    Here is a list of options that can be used with Bison, alphabetized
  3246. by short option.  It is followed by a cross key alphabetized by long
  3247. option.
  3248. `-b FILE-PREFIX'
  3249. `--file-prefix=PREFIX'
  3250.      Specify a prefix to use for all Bison output file names.  The
  3251.      names are chosen as if the input file were named `PREFIX.c'.
  3252. `--defines'
  3253.      Write an extra output file containing macro definitions for the
  3254.      token type names defined in the grammar and the semantic value type
  3255.      `YYSTYPE', as well as a few `extern' variable declarations.
  3256.      If the parser output file is named `NAME.c' then this file is
  3257.      named `NAME.h'.
  3258.      This output file is essential if you wish to put the definition of
  3259.      `yylex' in a separate source file, because `yylex' needs to be
  3260.      able to refer to token type codes and the variable `yylval'.
  3261.      *Note Semantic Values of Tokens: Token Values.
  3262. `--no-lines'
  3263.      Don't put any `#line' preprocessor commands in the parser file.
  3264.      Ordinarily Bison puts them in the parser file so that the C
  3265.      compiler and debuggers will associate errors with your source
  3266.      file, the grammar file.  This option causes them to associate
  3267.      errors with the parser file, treating it an independent source
  3268.      file in its own right.
  3269. `-o OUTFILE'
  3270. `--output-file=OUTFILE'
  3271.      Specify the name OUTFILE for the parser file.
  3272.      The other output files' names are constructed from OUTFILE as
  3273.      described under the `-v' and `-d' switches.
  3274. `-p PREFIX'
  3275. `--name-prefix=PREFIX'
  3276.      Rename the external symbols used in the parser so that they start
  3277.      with PREFIX instead of `yy'.  The precise list of symbols renamed
  3278.      is `yyparse', `yylex', `yyerror', `yylval', `yychar' and `yydebug'.
  3279.      For example, if you use `-p c', the names become `cparse', `clex',
  3280.      and so on.
  3281.      *Note Multiple Parsers in the Same Program: Multiple Parsers.
  3282. `--debug'
  3283.      Output a definition of the macro `YYDEBUG' into the parser file,
  3284.      so that the debugging facilities are compiled.  *Note Debugging
  3285.      Your Parser: Debugging.
  3286. `--verbose'
  3287.      Write an extra output file containing verbose descriptions of the
  3288.      parser states and what is done for each type of look-ahead token in
  3289.      that state.
  3290.      This file also describes all the conflicts, both those resolved by
  3291.      operator precedence and the unresolved ones.
  3292.      The file's name is made by removing `.tab.c' or `.c' from the
  3293.      parser output file name, and adding `.output' instead.
  3294.      Therefore, if the input file is `foo.y', then the parser file is
  3295.      called `foo.tab.c' by default.  As a consequence, the verbose
  3296.      output file is called `foo.output'.
  3297. `--version'
  3298.      Print the version number of Bison and exit.
  3299. `--help'
  3300.      Print a summary of the command-line options to Bison and exit.
  3301. `--yacc'
  3302. `--fixed-output-files'
  3303.      Equivalent to `-o y.tab.c'; the parser output file is called
  3304.      `y.tab.c', and the other outputs are called `y.output' and
  3305.      `y.tab.h'.  The purpose of this switch is to imitate Yacc's output
  3306.      file name conventions.  Thus, the following shell script can
  3307.      substitute for Yacc:
  3308.           bison -y $*
  3309. File: bison,  Node: Option Cross Key,  Next: VMS Invocation,  Prev: Bison Options,  Up: Invocation
  3310. Option Cross Key
  3311. ================
  3312.    Here is a list of options, alphabetized by long option, to help you
  3313. find the corresponding short option.
  3314.      --debug                               -t
  3315.      --defines                             -d
  3316.      --file-prefix=PREFIX                  -b FILE-PREFIX
  3317.      --fixed-output-files --yacc           -y
  3318.      --help                                -h
  3319.      --name-prefix                         -p
  3320.      --no-lines                            -l
  3321.      --output-file=OUTFILE                 -o OUTFILE
  3322.      --verbose                             -v
  3323.      --version                             -V
  3324. File: bison,  Node: VMS Invocation,  Prev: Option Cross Key,  Up: Invocation
  3325. Invoking Bison under VMS
  3326. ========================
  3327.    The command line syntax for Bison on VMS is a variant of the usual
  3328. Bison command syntax--adapted to fit VMS conventions.
  3329.    To find the VMS equivalent for any Bison option, start with the long
  3330. option, and substitute a `/' for the leading `--', and substitute a `_'
  3331. for each `-' in the name of the long option.  For example, the
  3332. following invocation under VMS:
  3333.      bison /debug/name_prefix=bar foo.y
  3334. is equivalent to the following command under POSIX.
  3335.      bison --debug --name-prefix=bar foo.y
  3336.    The VMS file system does not permit filenames such as `foo.tab.c'.
  3337. In the above example, the output file would instead be named
  3338. `foo_tab.c'.
  3339. File: bison,  Node: Table of Symbols,  Next: Glossary,  Prev: Invocation,  Up: Top
  3340. Bison Symbols
  3341. *************
  3342. `error'
  3343.      A token name reserved for error recovery.  This token may be used
  3344.      in grammar rules so as to allow the Bison parser to recognize an
  3345.      error in the grammar without halting the process.  In effect, a
  3346.      sentence containing an error may be recognized as valid.  On a
  3347.      parse error, the token `error' becomes the current look-ahead
  3348.      token.  Actions corresponding to `error' are then executed, and
  3349.      the look-ahead token is reset to the token that originally caused
  3350.      the violation.  *Note Error Recovery::.
  3351. `YYABORT'
  3352.      Macro to pretend that an unrecoverable syntax error has occurred,
  3353.      by making `yyparse' return 1 immediately.  The error reporting
  3354.      function `yyerror' is not called.  *Note The Parser Function
  3355.      `yyparse': Parser Function.
  3356. `YYACCEPT'
  3357.      Macro to pretend that a complete utterance of the language has been
  3358.      read, by making `yyparse' return 0 immediately.  *Note The Parser
  3359.      Function `yyparse': Parser Function.
  3360. `YYBACKUP'
  3361.      Macro to discard a value from the parser stack and fake a
  3362.      look-ahead token.  *Note Special Features for Use in Actions:
  3363.      Action Features.
  3364. `YYERROR'
  3365.      Macro to pretend that a syntax error has just been detected: call
  3366.      `yyerror' and then perform normal error recovery if possible
  3367.      (*note Error Recovery::.), or (if recovery is impossible) make
  3368.      `yyparse' return 1.  *Note Error Recovery::.
  3369. `YYERROR_VERBOSE'
  3370.      Macro that you define with `#define' in the Bison declarations
  3371.      section to request verbose, specific error message strings when
  3372.      `yyerror' is called.
  3373. `YYINITDEPTH'
  3374.      Macro for specifying the initial size of the parser stack.  *Note
  3375.      Stack Overflow::.
  3376. `YYLTYPE'
  3377.      Macro for the data type of `yylloc'; a structure with four
  3378.      members.  *Note Textual Positions of Tokens: Token Positions.
  3379. `YYMAXDEPTH'
  3380.      Macro for specifying the maximum size of the parser stack.  *Note
  3381.      Stack Overflow::.
  3382. `YYRECOVERING'
  3383.      Macro whose value indicates whether the parser is recovering from a
  3384.      syntax error.  *Note Special Features for Use in Actions: Action
  3385.      Features.
  3386. `YYSTYPE'
  3387.      Macro for the data type of semantic values; `int' by default.
  3388.      *Note Data Types of Semantic Values: Value Type.
  3389. `yychar'
  3390.      External integer variable that contains the integer value of the
  3391.      current look-ahead token.  (In a pure parser, it is a local
  3392.      variable within `yyparse'.)  Error-recovery rule actions may
  3393.      examine this variable.  *Note Special Features for Use in Actions:
  3394.      Action Features.
  3395. `yyclearin'
  3396.      Macro used in error-recovery rule actions.  It clears the previous
  3397.      look-ahead token.  *Note Error Recovery::.
  3398. `yydebug'
  3399.      External integer variable set to zero by default.  If `yydebug' is
  3400.      given a nonzero value, the parser will output information on input
  3401.      symbols and parser action.  *Note Debugging Your Parser: Debugging.
  3402. `yyerrok'
  3403.      Macro to cause parser to recover immediately to its normal mode
  3404.      after a parse error.  *Note Error Recovery::.
  3405. `yyerror'
  3406.      User-supplied function to be called by `yyparse' on error.  The
  3407.      function receives one argument, a pointer to a character string
  3408.      containing an error message.  *Note The Error Reporting Function
  3409.      `yyerror': Error Reporting.
  3410. `yylex'
  3411.      User-supplied lexical analyzer function, called with no arguments
  3412.      to get the next token.  *Note The Lexical Analyzer Function
  3413.      `yylex': Lexical.
  3414. `yylval'
  3415.      External variable in which `yylex' should place the semantic value
  3416.      associated with a token.  (In a pure parser, it is a local
  3417.      variable within `yyparse', and its address is passed to `yylex'.)
  3418.      *Note Semantic Values of Tokens: Token Values.
  3419. `yylloc'
  3420.      External variable in which `yylex' should place the line and
  3421.      column numbers associated with a token.  (In a pure parser, it is a
  3422.      local variable within `yyparse', and its address is passed to
  3423.      `yylex'.)  You can ignore this variable if you don't use the `@'
  3424.      feature in the grammar actions.  *Note Textual Positions of
  3425.      Tokens: Token Positions.
  3426. `yynerrs'
  3427.      Global variable which Bison increments each time there is a parse
  3428.      error.  (In a pure parser, it is a local variable within
  3429.      `yyparse'.)  *Note The Error Reporting Function `yyerror': Error
  3430.      Reporting.
  3431. `yyparse'
  3432.      The parser function produced by Bison; call this function to start
  3433.      parsing.  *Note The Parser Function `yyparse': Parser Function.
  3434. `%left'
  3435.      Bison declaration to assign left associativity to token(s).  *Note
  3436.      Operator Precedence: Precedence Decl.
  3437. `%nonassoc'
  3438.      Bison declaration to assign nonassociativity to token(s).  *Note
  3439.      Operator Precedence: Precedence Decl.
  3440. `%prec'
  3441.      Bison declaration to assign a precedence to a specific rule.
  3442.      *Note Context-Dependent Precedence: Contextual Precedence.
  3443. `%pure_parser'
  3444.      Bison declaration to request a pure (reentrant) parser.  *Note A
  3445.      Pure (Reentrant) Parser: Pure Decl.
  3446. `%right'
  3447.      Bison declaration to assign right associativity to token(s).
  3448.      *Note Operator Precedence: Precedence Decl.
  3449. `%start'
  3450.      Bison declaration to specify the start symbol.  *Note The
  3451.      Start-Symbol: Start Decl.
  3452. `%token'
  3453.      Bison declaration to declare token(s) without specifying
  3454.      precedence.  *Note Token Type Names: Token Decl.
  3455. `%type'
  3456.      Bison declaration to declare nonterminals.  *Note Nonterminal
  3457.      Symbols: Type Decl.
  3458. `%union'
  3459.      Bison declaration to specify several possible data types for
  3460.      semantic values.  *Note The Collection of Value Types: Union Decl.
  3461.    These are the punctuation and delimiters used in Bison input:
  3462.      Delimiter used to separate the grammar rule section from the Bison
  3463.      declarations section or the additional C code section.  *Note The
  3464.      Overall Layout of a Bison Grammar: Grammar Layout.
  3465. `%{ %}'
  3466.      All code listed between `%{' and `%}' is copied directly to the
  3467.      output file uninterpreted.  Such code forms the "C declarations"
  3468.      section of the input file.  *Note Outline of a Bison Grammar:
  3469.      Grammar Outline.
  3470. `/*...*/'
  3471.      Comment delimiters, as in C.
  3472.      Separates a rule's result from its components.  *Note Syntax of
  3473.      Grammar Rules: Rules.
  3474.      Terminates a rule.  *Note Syntax of Grammar Rules: Rules.
  3475.      Separates alternate rules for the same result nonterminal.  *Note
  3476.      Syntax of Grammar Rules: Rules.
  3477. File: bison,  Node: Glossary,  Next: Index,  Prev: Table of Symbols,  Up: Top
  3478. Glossary
  3479. ********
  3480. Backus-Naur Form (BNF)
  3481.      Formal method of specifying context-free grammars.  BNF was first
  3482.      used in the `ALGOL-60' report, 1963.  *Note Languages and
  3483.      Context-Free Grammars: Language and Grammar.
  3484. Context-free grammars
  3485.      Grammars specified as rules that can be applied regardless of
  3486.      context.  Thus, if there is a rule which says that an integer can
  3487.      be used as an expression, integers are allowed *anywhere* an
  3488.      expression is permitted.  *Note Languages and Context-Free
  3489.      Grammars: Language and Grammar.
  3490. Dynamic allocation
  3491.      Allocation of memory that occurs during execution, rather than at
  3492.      compile time or on entry to a function.
  3493. Empty string
  3494.      Analogous to the empty set in set theory, the empty string is a
  3495.      character string of length zero.
  3496. Finite-state stack machine
  3497.      A "machine" that has discrete states in which it is said to exist
  3498.      at each instant in time.  As input to the machine is processed, the
  3499.      machine moves from state to state as specified by the logic of the
  3500.      machine.  In the case of the parser, the input is the language
  3501.      being parsed, and the states correspond to various stages in the
  3502.      grammar rules.  *Note The Bison Parser Algorithm: Algorithm.
  3503. Grouping
  3504.      A language construct that is (in general) grammatically divisible;
  3505.      for example, `expression' or `declaration' in C.  *Note Languages
  3506.      and Context-Free Grammars: Language and Grammar.
  3507. Infix operator
  3508.      An arithmetic operator that is placed between the operands on
  3509.      which it performs some operation.
  3510. Input stream
  3511.      A continuous flow of data between devices or programs.
  3512. Language construct
  3513.      One of the typical usage schemas of the language.  For example,
  3514.      one of the constructs of the C language is the `if' statement.
  3515.      *Note Languages and Context-Free Grammars: Language and Grammar.
  3516. Left associativity
  3517.      Operators having left associativity are analyzed from left to
  3518.      right: `a+b+c' first computes `a+b' and then combines with `c'.
  3519.      *Note Operator Precedence: Precedence.
  3520. Left recursion
  3521.      A rule whose result symbol is also its first component symbol; for
  3522.      example, `expseq1 : expseq1 ',' exp;'.  *Note Recursive Rules:
  3523.      Recursion.
  3524. Left-to-right parsing
  3525.      Parsing a sentence of a language by analyzing it token by token
  3526.      from left to right.  *Note The Bison Parser Algorithm: Algorithm.
  3527. Lexical analyzer (scanner)
  3528.      A function that reads an input stream and returns tokens one by
  3529.      one.  *Note The Lexical Analyzer Function `yylex': Lexical.
  3530. Lexical tie-in
  3531.      A flag, set by actions in the grammar rules, which alters the way
  3532.      tokens are parsed.  *Note Lexical Tie-ins::.
  3533. Look-ahead token
  3534.      A token already read but not yet shifted.  *Note Look-Ahead
  3535.      Tokens: Look-Ahead.
  3536. LALR(1)
  3537.      The class of context-free grammars that Bison (like most other
  3538.      parser generators) can handle; a subset of LR(1).  *Note
  3539.      Mysterious Reduce/Reduce Conflicts: Mystery Conflicts.
  3540. LR(1)
  3541.      The class of context-free grammars in which at most one token of
  3542.      look-ahead is needed to disambiguate the parsing of any piece of
  3543.      input.
  3544. Nonterminal symbol
  3545.      A grammar symbol standing for a grammatical construct that can be
  3546.      expressed through rules in terms of smaller constructs; in other
  3547.      words, a construct that is not a token.  *Note Symbols::.
  3548. Parse error
  3549.      An error encountered during parsing of an input stream due to
  3550.      invalid syntax.  *Note Error Recovery::.
  3551. Parser
  3552.      A function that recognizes valid sentences of a language by
  3553.      analyzing the syntax structure of a set of tokens passed to it
  3554.      from a lexical analyzer.
  3555. Postfix operator
  3556.      An arithmetic operator that is placed after the operands upon
  3557.      which it performs some operation.
  3558. Reduction
  3559.      Replacing a string of nonterminals and/or terminals with a single
  3560.      nonterminal, according to a grammar rule.  *Note The Bison Parser
  3561.      Algorithm: Algorithm.
  3562. Reentrant
  3563.      A reentrant subprogram is a subprogram which can be in invoked any
  3564.      number of times in parallel, without interference between the
  3565.      various invocations.  *Note A Pure (Reentrant) Parser: Pure Decl.
  3566. Reverse polish notation
  3567.      A language in which all operators are postfix operators.
  3568. Right recursion
  3569.      A rule whose result symbol is also its last component symbol; for
  3570.      example, `expseq1: exp ',' expseq1;'.  *Note Recursive Rules:
  3571.      Recursion.
  3572. Semantics
  3573.      In computer languages, the semantics are specified by the actions
  3574.      taken for each instance of the language, i.e., the meaning of each
  3575.      statement.  *Note Defining Language Semantics: Semantics.
  3576. Shift
  3577.      A parser is said to shift when it makes the choice of analyzing
  3578.      further input from the stream rather than reducing immediately some
  3579.      already-recognized rule.  *Note The Bison Parser Algorithm:
  3580.      Algorithm.
  3581. Single-character literal
  3582.      A single character that is recognized and interpreted as is.
  3583.      *Note From Formal Rules to Bison Input: Grammar in Bison.
  3584. Start symbol
  3585.      The nonterminal symbol that stands for a complete valid utterance
  3586.      in the language being parsed.  The start symbol is usually listed
  3587.      as the first nonterminal symbol in a language specification.
  3588.      *Note The Start-Symbol: Start Decl.
  3589. Symbol table
  3590.      A data structure where symbol names and associated data are stored
  3591.      during parsing to allow for recognition and use of existing
  3592.      information in repeated uses of a symbol.  *Note Multi-function
  3593.      Calc::.
  3594. Token
  3595.      A basic, grammatically indivisible unit of a language.  The symbol
  3596.      that describes a token in the grammar is a terminal symbol.  The
  3597.      input of the Bison parser is a stream of tokens which comes from
  3598.      the lexical analyzer.  *Note Symbols::.
  3599. Terminal symbol
  3600.      A grammar symbol that has no rules in the grammar and therefore is
  3601.      grammatically indivisible.  The piece of text it represents is a
  3602.      token.  *Note Languages and Context-Free Grammars: Language and
  3603.      Grammar.
  3604. File: bison,  Node: Index,  Prev: Glossary,  Up: Top
  3605. Index
  3606. *****
  3607. * Menu:
  3608. * $$:                                   Actions.
  3609. * $N:                                   Actions.
  3610. * %expect:                              Expect Decl.
  3611. * %left:                                Using Precedence.
  3612. * %nonassoc:                            Using Precedence.
  3613. * %prec:                                Contextual Precedence.
  3614. * %pure_parser:                         Pure Decl.
  3615. * %right:                               Using Precedence.
  3616. * %start:                               Start Decl.
  3617. * %token:                               Token Decl.
  3618. * %type:                                Type Decl.
  3619. * %union:                               Union Decl.
  3620. * @N:                                   Action Features.
  3621. * calc:                                 Infix Calc.
  3622. * else, dangling:                       Shift/Reduce.
  3623. * mfcalc:                               Multi-function Calc.
  3624. * rpcalc:                               RPN Calc.
  3625. * action:                               Actions.
  3626. * action data types:                    Action Types.
  3627. * action features summary:              Action Features.
  3628. * actions in mid-rule:                  Mid-Rule Actions.
  3629. * actions, semantic:                    Semantic Actions.
  3630. * additional C code section:            C Code.
  3631. * algorithm of parser:                  Algorithm.
  3632. * associativity:                        Why Precedence.
  3633. * Backus-Naur form:                     Language and Grammar.
  3634. * Bison declaration summary:            Decl Summary.
  3635. * Bison declarations:                   Declarations.
  3636. * Bison declarations (introduction):    Bison Declarations.
  3637. * Bison grammar:                        Grammar in Bison.
  3638. * Bison invocation:                     Invocation.
  3639. * Bison parser:                         Bison Parser.
  3640. * Bison parser algorithm:               Algorithm.
  3641. * Bison symbols, table of:              Table of Symbols.
  3642. * Bison utility:                        Bison Parser.
  3643. * BNF:                                  Language and Grammar.
  3644. * C code, section for additional:       C Code.
  3645. * C declarations section:               C Declarations.
  3646. * C-language interface:                 Interface.
  3647. * calculator, infix notation:           Infix Calc.
  3648. * calculator, multi-function:           Multi-function Calc.
  3649. * calculator, simple:                   RPN Calc.
  3650. * character token:                      Symbols.
  3651. * compiling the parser:                 Rpcalc Compile.
  3652. * conflicts:                            Shift/Reduce.
  3653. * conflicts, reduce/reduce:             Reduce/Reduce.
  3654. * conflicts, suppressing warnings of:   Expect Decl.
  3655. * context-dependent precedence:         Contextual Precedence.
  3656. * context-free grammar:                 Language and Grammar.
  3657. * controlling function:                 Rpcalc Main.
  3658. * dangling else:                        Shift/Reduce.
  3659. * data types in actions:                Action Types.
  3660. * data types of semantic values:        Value Type.
  3661. * debugging:                            Debugging.
  3662. * declaration summary:                  Decl Summary.
  3663. * declarations, Bison:                  Declarations.
  3664. * declarations, Bison (introduction):   Bison Declarations.
  3665. * declarations, C:                      C Declarations.
  3666. * declaring operator precedence:        Precedence Decl.
  3667. * declaring the start symbol:           Start Decl.
  3668. * declaring token type names:           Token Decl.
  3669. * declaring value types:                Union Decl.
  3670. * declaring value types, nonterminals:  Type Decl.
  3671. * default action:                       Actions.
  3672. * default data type:                    Value Type.
  3673. * default stack limit:                  Stack Overflow.
  3674. * default start symbol:                 Start Decl.
  3675. * defining language semantics:          Semantics.
  3676. * error:                                Error Recovery.
  3677. * error recovery:                       Error Recovery.
  3678. * error recovery, simple:               Simple Error Recovery.
  3679. * error reporting function:             Error Reporting.
  3680. * error reporting routine:              Rpcalc Error.
  3681. * examples, simple:                     Examples.
  3682. * exercises:                            Exercises.
  3683. * file format:                          Grammar Layout.
  3684. * finite-state machine:                 Parser States.
  3685. * formal grammar:                       Grammar in Bison.
  3686. * format of grammar file:               Grammar Layout.
  3687. * glossary:                             Glossary.
  3688. * grammar file:                         Grammar Layout.
  3689. * grammar rule syntax:                  Rules.
  3690. * grammar rules section:                Grammar Rules.
  3691. * grammar, Bison:                       Grammar in Bison.
  3692. * grammar, context-free:                Language and Grammar.
  3693. * grouping, syntactic:                  Language and Grammar.
  3694. * infix notation calculator:            Infix Calc.
  3695. * interface:                            Interface.
  3696. * introduction:                         Introduction.
  3697. * invoking Bison:                       Invocation.
  3698. * invoking Bison under VMS:             VMS Invocation.
  3699. * LALR(1):                              Mystery Conflicts.
  3700. * language semantics, defining:         Semantics.
  3701. * layout of Bison grammar:              Grammar Layout.
  3702. * left recursion:                       Recursion.
  3703. * lexical analyzer:                     Lexical.
  3704. * lexical analyzer, purpose:            Bison Parser.
  3705. * lexical analyzer, writing:            Rpcalc Lexer.
  3706. * lexical tie-in:                       Lexical Tie-ins.
  3707. * literal token:                        Symbols.
  3708. * look-ahead token:                     Look-Ahead.
  3709. * LR(1):                                Mystery Conflicts.
  3710. * main function in simple example:      Rpcalc Main.
  3711. * mid-rule actions:                     Mid-Rule Actions.
  3712. * multi-function calculator:            Multi-function Calc.
  3713. * mutual recursion:                     Recursion.
  3714. * nonterminal symbol:                   Symbols.
  3715. * operator precedence:                  Precedence.
  3716. * operator precedence, declaring:       Precedence Decl.
  3717. * options for invoking Bison:           Invocation.
  3718. * overflow of parser stack:             Stack Overflow.
  3719. * parse error:                          Error Reporting.
  3720. * parser:                               Bison Parser.
  3721. * parser stack:                         Algorithm.
  3722. * parser stack overflow:                Stack Overflow.
  3723. * parser state:                         Parser States.
  3724. * polish notation calculator:           RPN Calc.
  3725. * precedence declarations:              Precedence Decl.
  3726. * precedence of operators:              Precedence.
  3727. * precedence, context-dependent:        Contextual Precedence.
  3728. * precedence, unary operator:           Contextual Precedence.
  3729. * preventing warnings about conflicts:  Expect Decl.
  3730. * pure parser:                          Pure Decl.
  3731. * recovery from errors:                 Error Recovery.
  3732. * recursive rule:                       Recursion.
  3733. * reduce/reduce conflict:               Reduce/Reduce.
  3734. * reduction:                            Algorithm.
  3735. * reentrant parser:                     Pure Decl.
  3736. * reverse polish notation:              RPN Calc.
  3737. * right recursion:                      Recursion.
  3738. * rule syntax:                          Rules.
  3739. * rules section for grammar:            Grammar Rules.
  3740. * running Bison (introduction):         Rpcalc Gen.
  3741. * semantic actions:                     Semantic Actions.
  3742. * semantic value:                       Semantic Values.
  3743. * semantic value type:                  Value Type.
  3744. * shift/reduce conflicts:               Shift/Reduce.
  3745. * shifting:                             Algorithm.
  3746. * simple examples:                      Examples.
  3747. * single-character literal:             Symbols.
  3748. * stack overflow:                       Stack Overflow.
  3749. * stack, parser:                        Algorithm.
  3750. * stages in using Bison:                Stages.
  3751. * start symbol:                         Language and Grammar.
  3752. * start symbol, declaring:              Start Decl.
  3753. * state (of parser):                    Parser States.
  3754. * summary, action features:             Action Features.
  3755. * summary, Bison declaration:           Decl Summary.
  3756. * suppressing conflict warnings:        Expect Decl.
  3757. * symbol:                               Symbols.
  3758. * symbol table example:                 Mfcalc Symtab.
  3759. * symbols (abstract):                   Language and Grammar.
  3760. * symbols in Bison, table of:           Table of Symbols.
  3761. * syntactic grouping:                   Language and Grammar.
  3762. * syntax error:                         Error Reporting.
  3763. * syntax of grammar rules:              Rules.
  3764. * terminal symbol:                      Symbols.
  3765. * token:                                Language and Grammar.
  3766. * token type:                           Symbols.
  3767. * token type names, declaring:          Token Decl.
  3768. * tracing the parser:                   Debugging.
  3769. * unary operator precedence:            Contextual Precedence.
  3770. * using Bison:                          Stages.
  3771. * value type, semantic:                 Value Type.
  3772. * value types, declaring:               Union Decl.
  3773. * value types, nonterminals, declaring: Type Decl.
  3774. * value, semantic:                      Semantic Values.
  3775. * VMS:                                  VMS Invocation.
  3776. * warnings, preventing:                 Expect Decl.
  3777. * writing a lexical analyzer:           Rpcalc Lexer.
  3778. * YYABORT:                              Parser Function.
  3779. * YYACCEPT:                             Parser Function.
  3780. * YYBACKUP:                             Action Features.
  3781. * yychar:                               Look-Ahead.
  3782. * yyclearin:                            Error Recovery.
  3783. * YYDEBUG:                              Debugging.
  3784. * yydebug:                              Debugging.
  3785. * YYEMPTY:                              Action Features.
  3786. * yyerrok:                              Error Recovery.
  3787. * YYERROR:                              Action Features.
  3788. * yyerror:                              Error Reporting.
  3789. * YYERROR_VERBOSE:                      Error Reporting.
  3790. * YYINITDEPTH:                          Stack Overflow.
  3791. * yylex:                                Lexical.
  3792. * yylloc:                               Token Positions.
  3793. * YYLTYPE:                              Token Positions.
  3794. * yylval:                               Token Values.
  3795. * YYMAXDEPTH:                           Stack Overflow.
  3796. * yynerrs:                              Error Reporting.
  3797. * yyparse:                              Parser Function.
  3798. * YYPRINT:                              Debugging.
  3799. * YYRECOVERING:                         Error Recovery.
  3800. * |:                                    Rules.
  3801. Tag Table:
  3802. Node: Top
  3803. Node: Introduction
  3804. Node: Conditions
  3805. Node: Copying
  3806. 11418
  3807. Node: Concepts
  3808. 30566
  3809. Node: Language and Grammar
  3810. 31594
  3811. Node: Grammar in Bison
  3812. 36605
  3813. Node: Semantic Values
  3814. 38378
  3815. Node: Semantic Actions
  3816. 40474
  3817. Node: Bison Parser
  3818. 41652
  3819. Node: Stages
  3820. 43957
  3821. Node: Grammar Layout
  3822. 45235
  3823. Node: Examples
  3824. 46487
  3825. Node: RPN Calc
  3826. 47617
  3827. Node: Rpcalc Decls
  3828. 48586
  3829. Node: Rpcalc Rules
  3830. 50168
  3831. Node: Rpcalc Input
  3832. 51963
  3833. Node: Rpcalc Line
  3834. 53419
  3835. Node: Rpcalc Expr
  3836. 54529
  3837. Node: Rpcalc Lexer
  3838. 56469
  3839. Node: Rpcalc Main
  3840. 59023
  3841. Node: Rpcalc Error
  3842. 59396
  3843. Node: Rpcalc Gen
  3844. 60396
  3845. Node: Rpcalc Compile
  3846. 61539
  3847. Node: Infix Calc
  3848. 62409
  3849. Node: Simple Error Recovery
  3850. 65111
  3851. Node: Multi-function Calc
  3852. 66993
  3853. Node: Mfcalc Decl
  3854. 68554
  3855. Node: Mfcalc Rules
  3856. 70572
  3857. Node: Mfcalc Symtab
  3858. 71947
  3859. Node: Exercises
  3860. 78116
  3861. Node: Grammar File
  3862. 78617
  3863. Node: Grammar Outline
  3864. 79380
  3865. Node: C Declarations
  3866. 80109
  3867. Node: Bison Declarations
  3868. 80684
  3869. Node: Grammar Rules
  3870. 81091
  3871. Node: C Code
  3872. 81546
  3873. Node: Symbols
  3874. 82471
  3875. Node: Rules
  3876. 86241
  3877. Node: Recursion
  3878. 87875
  3879. Node: Semantics
  3880. 89581
  3881. Node: Value Type
  3882. 90673
  3883. Node: Multiple Types
  3884. 91340
  3885. Node: Actions
  3886. 92351
  3887. Node: Action Types
  3888. 95131
  3889. Node: Mid-Rule Actions
  3890. 96429
  3891. Node: Declarations
  3892. 101993
  3893. Node: Token Decl
  3894. 103307
  3895. Node: Precedence Decl
  3896. 104625
  3897. Node: Union Decl
  3898. 106171
  3899. Node: Type Decl
  3900. 107010
  3901. Node: Expect Decl
  3902. 107710
  3903. Node: Start Decl
  3904. 109251
  3905. Node: Pure Decl
  3906. 109624
  3907. Node: Decl Summary
  3908. 110921
  3909. Node: Multiple Parsers
  3910. 112320
  3911. Node: Interface
  3912. 113798
  3913. Node: Parser Function
  3914. 114665
  3915. Node: Lexical
  3916. 115495
  3917. Node: Calling Convention
  3918. 116896
  3919. Node: Token Values
  3920. 118198
  3921. Node: Token Positions
  3922. 119341
  3923. Node: Pure Calling
  3924. 120228
  3925. Node: Error Reporting
  3926. 121223
  3927. Node: Action Features
  3928. 123343
  3929. Node: Algorithm
  3930. 126989
  3931. Node: Look-Ahead
  3932. 129277
  3933. Node: Shift/Reduce
  3934. 131404
  3935. Node: Precedence
  3936. 134310
  3937. Node: Why Precedence
  3938. 134956
  3939. Node: Using Precedence
  3940. 136806
  3941. Node: Precedence Examples
  3942. 137769
  3943. Node: How Precedence
  3944. 138465
  3945. Node: Contextual Precedence
  3946. 139609
  3947. Node: Parser States
  3948. 141395
  3949. Node: Reduce/Reduce
  3950. 142633
  3951. Node: Mystery Conflicts
  3952. 146189
  3953. Node: Stack Overflow
  3954. 149570
  3955. Node: Error Recovery
  3956. 150938
  3957. Node: Context Dependency
  3958. 156069
  3959. Node: Semantic Tokens
  3960. 156912
  3961. Node: Lexical Tie-ins
  3962. 159924
  3963. Node: Tie-in Recovery
  3964. 161467
  3965. Node: Debugging
  3966. 163634
  3967. Node: Invocation
  3968. 166980
  3969. Node: Bison Options
  3970. 167638
  3971. Node: Option Cross Key
  3972. 171270
  3973. Node: VMS Invocation
  3974. 171997
  3975. Node: Table of Symbols
  3976. 172776
  3977. Node: Glossary
  3978. 179358
  3979. Node: Index
  3980. 185537
  3981. End Tag Table
  3982.